Fix paste ownership, input bounds, and IPC validation
Supersedes #5745, #5746, and #5747.
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
DECORATIVE_AGENT_TITLE_SIGNATURE_SOURCE_SCAN_LIMIT,
|
||||
getDecorativeAgentTitleSignature,
|
||||
isDecorativeAgentTitleFrameChange
|
||||
} from './agent-decorative-title-signature'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
const BRAILLE_SPINNER_FRAME_A = String.fromCharCode(0x280b)
|
||||
const BRAILLE_SPINNER_FRAME_B = String.fromCharCode(0x2819)
|
||||
|
||||
describe('agent decorative title signatures', () => {
|
||||
it('treats spinner-only frame changes as the same decorative title', () => {
|
||||
expect(
|
||||
isDecorativeAgentTitleFrameChange(
|
||||
`${BRAILLE_SPINNER_FRAME_A} Codex is thinking`,
|
||||
`${BRAILLE_SPINNER_FRAME_B} Codex\tis\nthinking`
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('returns null for ordinary non-agent titles', () => {
|
||||
expect(getDecorativeAgentTitleSignature('vim src/index.ts')).toBeNull()
|
||||
})
|
||||
|
||||
it('folds title whitespace without full whitespace replacement', () => {
|
||||
const replace = vi.spyOn(String.prototype, 'replace')
|
||||
const title = ` \t${BRAILLE_SPINNER_FRAME_A}\t Codex is\nthinking ${' pasted text '.repeat(40)}`
|
||||
|
||||
expect(getDecorativeAgentTitleSignature(title)).toBe(
|
||||
`working:Codex is thinking ${'pasted text '.repeat(40).trimEnd()}`
|
||||
)
|
||||
expect(
|
||||
replace.mock.calls.filter(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+'
|
||||
)
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not normalize oversized title text on the hot path', () => {
|
||||
const replace = vi.spyOn(String.prototype, 'replace')
|
||||
const title = `${BRAILLE_SPINNER_FRAME_A} Codex is thinking ${'x'.repeat(
|
||||
DECORATIVE_AGENT_TITLE_SIGNATURE_SOURCE_SCAN_LIMIT + 1
|
||||
)}`
|
||||
|
||||
expect(getDecorativeAgentTitleSignature(title)).toBeNull()
|
||||
expect(replace).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { detectAgentStatusFromTitle, MAX_OSC_TITLE_CHARS } from './agent-detection'
|
||||
|
||||
export const DECORATIVE_AGENT_TITLE_SIGNATURE_SOURCE_SCAN_LIMIT = MAX_OSC_TITLE_CHARS
|
||||
|
||||
export function getDecorativeAgentTitleSignature(title: string): string | null {
|
||||
// Why: this runs on renderer state/session hot paths; oversized titles are
|
||||
// treated as ordinary changes instead of synchronously normalized.
|
||||
if (title.length > DECORATIVE_AGENT_TITLE_SIGNATURE_SOURCE_SCAN_LIMIT) {
|
||||
return null
|
||||
}
|
||||
const status = detectAgentStatusFromTitle(title)
|
||||
if (!status) {
|
||||
return null
|
||||
}
|
||||
// Why: agent spinners can emit OSC title frames many times per second; the
|
||||
// spinner glyph is live decoration, not meaningful tab or sort state.
|
||||
return `${status}:${normalizeDecorativeAgentTitleText(title)}`
|
||||
}
|
||||
|
||||
export function isDecorativeAgentTitleFrameChange(prevTitle: string, nextTitle: string): boolean {
|
||||
const prevSignature = getDecorativeAgentTitleSignature(prevTitle)
|
||||
return prevSignature !== null && prevSignature === getDecorativeAgentTitleSignature(nextTitle)
|
||||
}
|
||||
|
||||
function normalizeDecorativeAgentTitleText(title: string): string {
|
||||
let normalized = ''
|
||||
let pendingWhitespace = false
|
||||
for (let index = 0; index < title.length; index += 1) {
|
||||
const code = title.charCodeAt(index)
|
||||
if (normalized.length === 0 && (isDecorativeTitleWhitespace(code) || isBrailleSpinner(code))) {
|
||||
continue
|
||||
}
|
||||
if (isDecorativeTitleWhitespace(code)) {
|
||||
pendingWhitespace = normalized.length > 0
|
||||
continue
|
||||
}
|
||||
if (pendingWhitespace) {
|
||||
normalized += ' '
|
||||
pendingWhitespace = false
|
||||
}
|
||||
normalized += title.charAt(index)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function isBrailleSpinner(code: number): boolean {
|
||||
return code >= 0x2800 && code <= 0x28ff
|
||||
}
|
||||
|
||||
function isDecorativeTitleWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { extractAllOscTitles, extractLastOscTitle, MAX_OSC_TITLE_CHARS } from './agent-detection'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('OSC title extraction', () => {
|
||||
it('extracts the last OSC title from BEL-terminated PTY data', () => {
|
||||
expect(extractLastOscTitle('\x1b]0;First\x07noise\x1b]2;Second\x07')).toBe('Second')
|
||||
})
|
||||
|
||||
it('extracts all OSC titles including ST-terminated titles', () => {
|
||||
expect(extractAllOscTitles('\x1b]0;First\x1b\\noise\x1b]2;Second\x07')).toEqual([
|
||||
'First',
|
||||
'Second'
|
||||
])
|
||||
})
|
||||
|
||||
it('ignores incomplete OSC titles until a later chunk supplies the terminator', () => {
|
||||
expect(extractAllOscTitles('\x1b]0;Incomplete title')).toEqual([])
|
||||
expect(extractLastOscTitle('\x1b]0;Incomplete title')).toBeNull()
|
||||
})
|
||||
|
||||
it('recovers when an abandoned incomplete OSC title is followed by a fresh title', () => {
|
||||
const data = '\x1b]0;abandoned\x1b]0;Fresh title\x07'
|
||||
|
||||
expect(extractLastOscTitle(data)).toBe('Fresh title')
|
||||
expect(extractAllOscTitles(data)).toEqual(['Fresh title'])
|
||||
})
|
||||
|
||||
it('scans large PTY chunks without regex match iteration', () => {
|
||||
const matchAll = vi.spyOn(String.prototype, 'matchAll')
|
||||
const data = `${'pasted terminal noise \x1b]x;ignored\x07 '.repeat(10_000)}\x1b]0;Agent working\x07`
|
||||
|
||||
expect(extractLastOscTitle(data)).toBe('Agent working')
|
||||
expect(extractAllOscTitles(data).at(-1)).toBe('Agent working')
|
||||
expect(matchAll).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('caps oversized OSC titles before downstream title processing', () => {
|
||||
const title = `${'a'.repeat(MAX_OSC_TITLE_CHARS)}${'b'.repeat(10_000)}`
|
||||
const data = `before\x1b]0;${title}\x07after`
|
||||
|
||||
const extracted = extractLastOscTitle(data)
|
||||
|
||||
expect(extracted).toHaveLength(MAX_OSC_TITLE_CHARS)
|
||||
expect(extracted?.startsWith('a'.repeat(MAX_OSC_TITLE_CHARS / 2))).toBe(true)
|
||||
expect(extracted?.endsWith('b'.repeat(MAX_OSC_TITLE_CHARS / 2))).toBe(true)
|
||||
expect(extractAllOscTitles(data)).toEqual([extracted])
|
||||
})
|
||||
})
|
||||
@@ -17,6 +17,11 @@ import {
|
||||
|
||||
// Re-export so existing `agent-detection` importers keep working.
|
||||
export { AGENT_NAMES, titleHasAgentName } from './agent-name-token-match'
|
||||
export {
|
||||
extractAllOscTitles,
|
||||
extractLastOscTitle,
|
||||
MAX_OSC_TITLE_CHARS
|
||||
} from './osc-title-extraction'
|
||||
export { isShellProcess } from './shell-process-detection'
|
||||
|
||||
export type AgentStatus = 'working' | 'permission' | 'idle'
|
||||
@@ -89,47 +94,6 @@ export const STRONG_WORKING_KEYWORDS_RE = new RegExp(
|
||||
const STRONG_WORKING_KEYWORDS_RE_GLOBAL = new RegExp(STRONG_WORKING_KEYWORDS_RE.source, 'gi')
|
||||
const PI_IDLE_PREFIX = '\u03c0 - ' // π - (Pi titlebar extension idle format)
|
||||
|
||||
// eslint-disable-next-line no-control-regex -- intentional terminal escape sequence matching
|
||||
const OSC_TITLE_RE = /\x1b\]([012]);([^\x07\x1b]*?)(?:\x07|\x1b\\)/g
|
||||
|
||||
/**
|
||||
* Extract the last OSC title-set sequence from raw PTY data.
|
||||
* Agent CLIs (Claude Code, Gemini, etc.) set OSC titles to announce their
|
||||
* identity and status. This is a single regex scan — comparable cost to one
|
||||
* normalizeTerminalChunk pass.
|
||||
*/
|
||||
export function extractLastOscTitle(data: string): string | null {
|
||||
if (!data.includes('\x1b]')) {
|
||||
return null
|
||||
}
|
||||
let last: string | null = null
|
||||
for (const m of data.matchAll(OSC_TITLE_RE)) {
|
||||
last = m[2]
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract ALL OSC title-set sequences from raw PTY data, in order of appearance.
|
||||
* Why separate from extractLastOscTitle: node-pty and the main-process batch
|
||||
* window (PTY_BATCH_INTERVAL_MS) often coalesce multiple title changes into
|
||||
* one IPC payload. For fast agents (Pi's 80ms spinner + agent_end idle in the
|
||||
* same batch), returning only the last title silently drops the working
|
||||
* transition. Callers that care about driving UI state transitions
|
||||
* (working/idle spinner) need every title in the chunk. See issue #1083's
|
||||
* spinner-miss follow-up.
|
||||
*/
|
||||
export function extractAllOscTitles(data: string): string[] {
|
||||
if (!data.includes('\x1b]')) {
|
||||
return []
|
||||
}
|
||||
const titles: string[] = []
|
||||
for (const m of data.matchAll(OSC_TITLE_RE)) {
|
||||
titles.push(m[2])
|
||||
}
|
||||
return titles
|
||||
}
|
||||
|
||||
export function isGeminiTerminalTitle(title: string): boolean {
|
||||
return (
|
||||
title.includes(GEMINI_PERMISSION) ||
|
||||
|
||||
@@ -335,6 +335,70 @@ describe('shared agent-hook-listener', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('reads newline-heavy Command Code transcripts without line-array splitting', () => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-command-code-large-transcript-'))
|
||||
const transcriptPath = join(tmpDir, 'transcript.jsonl')
|
||||
try {
|
||||
const filler = Array.from({ length: 6_000 }, (_value, index) =>
|
||||
JSON.stringify({
|
||||
role: index % 2 === 0 ? 'assistant' : 'user',
|
||||
content: [{ type: 'text', text: `filler ${index}` }]
|
||||
})
|
||||
)
|
||||
writeFileSync(
|
||||
transcriptPath,
|
||||
`${[
|
||||
...filler,
|
||||
JSON.stringify({
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'large transcript prompt' }]
|
||||
}),
|
||||
JSON.stringify({
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'large transcript answer' }]
|
||||
})
|
||||
].join('\n')}\n`
|
||||
)
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
|
||||
const tool = normalizeHookPayload(
|
||||
state,
|
||||
'command-code',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hook_event_name: 'PreToolUse',
|
||||
transcript_path: transcriptPath,
|
||||
tool_name: 'shell_command',
|
||||
tool_input: { command: 'pwd' }
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
const done = normalizeHookPayload(
|
||||
state,
|
||||
'command-code',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hook_event_name: 'Stop',
|
||||
transcript_path: transcriptPath
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(tool?.payload.prompt).toBe('large transcript prompt')
|
||||
expect(done?.payload.lastAssistantMessage).toBe('large transcript answer')
|
||||
const usedLineArraySplit = splitSpy.mock.calls.some(
|
||||
([separator]) => typeof separator === 'string' && separator === '\n'
|
||||
)
|
||||
expect(usedLineArraySplit).toBe(false)
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('trims surrounding whitespace from extracted prompt text', () => {
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
@@ -728,6 +792,47 @@ describe('shared agent-hook-listener', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('reads newline-heavy Antigravity user requests without wrapper regex matching', () => {
|
||||
const matchSpy = vi.spyOn(String.prototype, 'match')
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-antigravity-large-prompt-'))
|
||||
const transcriptPath = join(tmpDir, 'transcript.jsonl')
|
||||
const requestText = 'Fix the failing test\n'.repeat(300)
|
||||
try {
|
||||
writeFileSync(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({
|
||||
source: 'USER_EXPLICIT',
|
||||
type: 'USER_INPUT',
|
||||
content: `<USER_REQUEST>\n${requestText}</USER_REQUEST>`
|
||||
})}\n`
|
||||
)
|
||||
|
||||
const started = normalizeHookPayload(
|
||||
state,
|
||||
'antigravity',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
hook_event_name: 'PreInvocation',
|
||||
payload: { transcriptPath }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(started?.payload.prompt).toContain('Fix the failing test')
|
||||
expect(started?.payload.prompt).not.toContain('<USER_REQUEST>')
|
||||
expect(started?.payload.prompt).not.toContain('</USER_REQUEST>')
|
||||
const usedRequestWrapperMatch = matchSpy.mock.calls.some(
|
||||
([pattern]) =>
|
||||
pattern instanceof RegExp &&
|
||||
pattern.source.includes('<USER_REQUEST>') &&
|
||||
pattern.source.includes('[\\s\\S]')
|
||||
)
|
||||
expect(usedRequestWrapperMatch).toBe(false)
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the cached Antigravity prompt instead of rescanning the transcript', () => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-antigravity-cached-prompt-'))
|
||||
const transcriptPath = join(tmpDir, 'transcript.jsonl')
|
||||
@@ -1094,6 +1199,34 @@ describe('shared agent-hook-listener', () => {
|
||||
expect(event?.payload.prompt).toBe('Find recent PR')
|
||||
})
|
||||
|
||||
it('strips newline-heavy Grok user_query wrappers without regex matching', () => {
|
||||
const matchSpy = vi.spyOn(String.prototype, 'match')
|
||||
const promptText = 'Find recent PR\n'.repeat(300)
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'user_prompt_submit',
|
||||
prompt: `<user_query>\n${promptText}</user_query>`
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(event?.payload.prompt).toContain('Find recent PR')
|
||||
expect(event?.payload.prompt).not.toContain('<user_query>')
|
||||
expect(event?.payload.prompt).not.toContain('</user_query>')
|
||||
const usedGrokWrapperMatch = matchSpy.mock.calls.some(
|
||||
([pattern]) =>
|
||||
pattern instanceof RegExp &&
|
||||
pattern.source.startsWith('^<user_query>') &&
|
||||
pattern.source.includes('[\\s\\S]')
|
||||
)
|
||||
expect(usedGrokWrapperMatch).toBe(false)
|
||||
})
|
||||
|
||||
it('maps Grok feedback notifications to waiting without overwriting the prompt', () => {
|
||||
normalizeHookPayload(
|
||||
state,
|
||||
|
||||
@@ -372,10 +372,16 @@ function extractPromptText(hookPayload: Record<string, unknown>): ExtractedPromp
|
||||
}
|
||||
|
||||
function stripGrokUserQueryWrapper(promptText: string): string {
|
||||
const match = promptText.match(/^<user_query>([\s\S]*?)(?:<\/user_query>)?$/)
|
||||
const opener = '<user_query>'
|
||||
if (!promptText.startsWith(opener)) {
|
||||
return promptText
|
||||
}
|
||||
const closer = '</user_query>'
|
||||
const wrappedText = promptText.slice(opener.length)
|
||||
const text = wrappedText.endsWith(closer) ? wrappedText.slice(0, -closer.length) : wrappedText
|
||||
// Why: Grok emits the submitted prompt wrapped in its internal
|
||||
// `<user_query>` envelope; the status cache should hold the user text.
|
||||
return match ? match[1].trim() : promptText
|
||||
return text.trim()
|
||||
}
|
||||
|
||||
function resolvePrompt(
|
||||
@@ -717,8 +723,12 @@ function extractAssistantContentText(content: unknown): string | undefined {
|
||||
}
|
||||
|
||||
function extractAntigravityUserRequest(content: string): string | undefined {
|
||||
const request = content.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/)
|
||||
const text = request ? request[1] : content
|
||||
const opener = '<USER_REQUEST>'
|
||||
const startIndex = content.indexOf(opener)
|
||||
const bodyStartIndex = startIndex === -1 ? -1 : startIndex + opener.length
|
||||
const endIndex = bodyStartIndex === -1 ? -1 : content.indexOf('</USER_REQUEST>', bodyStartIndex)
|
||||
const text =
|
||||
bodyStartIndex === -1 || endIndex === -1 ? content : content.slice(bodyStartIndex, endIndex)
|
||||
const trimmed = text.trim()
|
||||
return trimmed.length > 0 ? trimmed : undefined
|
||||
}
|
||||
@@ -810,14 +820,12 @@ function readLastCommandCodeUserPromptEntryFromTranscript(
|
||||
}
|
||||
let lastPrompt: string | undefined
|
||||
let lastPromptOffset = 0
|
||||
let lineStart = 0
|
||||
for (const line of text.split('\n')) {
|
||||
for (const { line, byteOffset } of iterateTranscriptLinesWithByteOffsets(text)) {
|
||||
const prompt = extractCommandCodeUserPromptFromLine(line.trim())
|
||||
if (prompt !== undefined) {
|
||||
lastPrompt = prompt
|
||||
lastPromptOffset = textBasePosition + Buffer.byteLength(text.slice(0, lineStart), 'utf8')
|
||||
lastPromptOffset = textBasePosition + byteOffset
|
||||
}
|
||||
lineStart += line.length + 1
|
||||
}
|
||||
return lastPrompt
|
||||
? {
|
||||
@@ -838,6 +846,24 @@ function readLastCommandCodeUserPromptEntryFromTranscript(
|
||||
}
|
||||
}
|
||||
|
||||
function* iterateTranscriptLinesWithByteOffsets(
|
||||
text: string
|
||||
): Generator<{ line: string; byteOffset: number }> {
|
||||
let lineStart = 0
|
||||
let byteOffset = 0
|
||||
|
||||
for (let index = 0; index <= text.length; index++) {
|
||||
if (index < text.length && text.charCodeAt(index) !== 10) {
|
||||
continue
|
||||
}
|
||||
|
||||
const line = text.slice(lineStart, index)
|
||||
yield { line, byteOffset }
|
||||
byteOffset += Buffer.byteLength(line, 'utf8') + (index < text.length ? 1 : 0)
|
||||
lineStart = index + 1
|
||||
}
|
||||
}
|
||||
|
||||
function extractCommandCodeAssistantTextFromLine(line: string): string | undefined {
|
||||
let entry: unknown
|
||||
try {
|
||||
@@ -1034,16 +1060,12 @@ function readLastTextFromTranscriptOnce(
|
||||
completeRegion = combined.subarray(firstNewline + 1)
|
||||
}
|
||||
if (completeRegion.length > 0) {
|
||||
const lines = completeRegion.toString('utf8').split('\n')
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i].trim()
|
||||
if (line.length === 0) {
|
||||
continue
|
||||
}
|
||||
const extracted = extractLineText(line)
|
||||
if (extracted !== undefined) {
|
||||
return extracted
|
||||
}
|
||||
const extracted = findLastExtractedTranscriptLineText(
|
||||
completeRegion.toString('utf8'),
|
||||
extractLineText
|
||||
)
|
||||
if (extracted !== undefined) {
|
||||
return extracted
|
||||
}
|
||||
}
|
||||
carryBytes = nextCarry
|
||||
@@ -1057,6 +1079,30 @@ function readLastTextFromTranscriptOnce(
|
||||
}
|
||||
}
|
||||
|
||||
function findLastExtractedTranscriptLineText(
|
||||
text: string,
|
||||
extractLineText: (line: string) => string | undefined
|
||||
): string | undefined {
|
||||
let lineEnd = text.length
|
||||
|
||||
for (let index = text.length - 1; index >= -1; index--) {
|
||||
if (index >= 0 && text.charCodeAt(index) !== 10) {
|
||||
continue
|
||||
}
|
||||
|
||||
const line = text.slice(index + 1, lineEnd).trim()
|
||||
if (line.length > 0) {
|
||||
const extracted = extractLineText(line)
|
||||
if (extracted !== undefined) {
|
||||
return extracted
|
||||
}
|
||||
}
|
||||
lineEnd = index
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
function extractClaudeToolFields(
|
||||
eventName: unknown,
|
||||
hookPayload: Record<string, unknown>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { getTuiAgentDetectCommands, TUI_AGENT_CONFIG } from './tui-agent-config'
|
||||
import type { AgentType } from './agent-status-types'
|
||||
import type { TuiAgent } from './types'
|
||||
import { filterHeadlessOneShotAgentCommand } from './agent-headless-command'
|
||||
import { getFirstCommandToken } from './command-token-scanner'
|
||||
|
||||
export type RecognizedAgentProcess = { agent: TuiAgent; processName: string }
|
||||
|
||||
@@ -25,10 +26,6 @@ function normalizeProcessName(
|
||||
return withoutProcessExtension
|
||||
}
|
||||
|
||||
function firstCommandToken(command: string): string {
|
||||
return command.trim().split(/\s+/)[0] ?? ''
|
||||
}
|
||||
|
||||
const STATIC_INTERPRETER_PROCESS_NAMES = new Set([
|
||||
'node',
|
||||
'python',
|
||||
@@ -68,7 +65,7 @@ for (const [agent, config] of Object.entries(TUI_AGENT_CONFIG) as [
|
||||
for (const candidate of [
|
||||
config.expectedProcess,
|
||||
...getTuiAgentDetectCommands(config),
|
||||
firstCommandToken(config.launchCmd)
|
||||
getFirstCommandToken(config.launchCmd)
|
||||
]) {
|
||||
const normalized = normalizeProcessName(candidate)
|
||||
if (normalized) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
parseAgentStatusPayload,
|
||||
normalizeAgentStatusPayload,
|
||||
AGENT_STATUS_MAX_FIELD_LENGTH,
|
||||
AGENT_STATUS_TOOL_NAME_MAX_LENGTH,
|
||||
AGENT_STATUS_TOOL_INPUT_MAX_LENGTH,
|
||||
@@ -9,6 +10,10 @@ import {
|
||||
AGENT_TYPE_MAX_LENGTH
|
||||
} from './agent-status-types'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('parseAgentStatusPayload', () => {
|
||||
it('parses a valid working payload', () => {
|
||||
const result = parseAgentStatusPayload(
|
||||
@@ -185,6 +190,34 @@ describe('parseAgentStatusPayload', () => {
|
||||
expect(result!.toolInput).toBe('line one line two')
|
||||
})
|
||||
|
||||
it('normalizes large single-line preview fields without full-string replacement passes', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const prompt = `Summary\r\nDetails ${'x'.repeat(20_000)}`
|
||||
const toolInput = `src/index.ts${String.fromCharCode(0x2028)}${'line\n'.repeat(10_000)}`
|
||||
|
||||
const result = normalizeAgentStatusPayload({
|
||||
state: 'working',
|
||||
prompt,
|
||||
toolInput
|
||||
})
|
||||
|
||||
expect(result!.prompt.startsWith('Summary Details ')).toBe(true)
|
||||
expect(result!.prompt).toHaveLength(AGENT_STATUS_MAX_FIELD_LENGTH)
|
||||
expect(result!.toolInput?.startsWith('src/index.ts ')).toBe(true)
|
||||
expect(result!.toolInput!.length).toBeLessThanOrEqual(AGENT_STATUS_TOOL_INPUT_MAX_LENGTH)
|
||||
expect(replaceSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('bounds scanning when oversized single-line previews are mostly line breaks', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const prompt = `Summary${'\n'.repeat(10_000)}Details`
|
||||
|
||||
const result = normalizeAgentStatusPayload({ state: 'working', prompt })
|
||||
|
||||
expect(result!.prompt).toBe('Summary')
|
||||
expect(replaceSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves paragraph breaks in lastAssistantMessage', () => {
|
||||
// Why: the assistant message is rendered with `whitespace-pre-wrap` in the
|
||||
// dashboard row so the user sees the same paragraph structure the agent
|
||||
@@ -202,6 +235,26 @@ describe('parseAgentStatusPayload', () => {
|
||||
expect(result!.lastAssistantMessage).toBe('a\nb\n\nc')
|
||||
})
|
||||
|
||||
it('normalizes large assistant messages without full-string replacement passes', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const lastAssistantMessage = `Summary\r\n${'\r\n'.repeat(10_000)}Details ${'x'.repeat(
|
||||
AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH
|
||||
)}`
|
||||
|
||||
const result = parseAgentStatusPayload(JSON.stringify({ state: 'done', lastAssistantMessage }))
|
||||
|
||||
expect(result!.lastAssistantMessage?.startsWith('Summary\n\nDetails ')).toBe(true)
|
||||
expect(result!.lastAssistantMessage!.length).toBeLessThanOrEqual(
|
||||
AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH
|
||||
)
|
||||
const usedMultilineReplace = replaceSpy.mock.calls.some(
|
||||
([pattern]) =>
|
||||
pattern instanceof RegExp &&
|
||||
['\\r\\n', '\\r', '[\\u2028\\u2029]', '\\n{3,}'].includes(pattern.source)
|
||||
)
|
||||
expect(usedMultilineReplace).toBe(false)
|
||||
})
|
||||
|
||||
it('folds Unicode line/paragraph separators into \\n and caps blank-line runs in lastAssistantMessage', () => {
|
||||
// Why: U+2028 and U+2029 render as real line breaks under
|
||||
// `whitespace-pre-wrap`. Without folding them to `\n`, a payload with
|
||||
|
||||
@@ -203,6 +203,8 @@ export const AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH = 8000
|
||||
* dashboard + hover only display hook-reported data as-is.
|
||||
*/
|
||||
export const AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000
|
||||
const SINGLE_LINE_FIELD_SCAN_OVERHEAD = 64
|
||||
const SINGLE_LINE_FIELD_SCAN_MULTIPLIER = 8
|
||||
|
||||
// Why: typed as ReadonlySet<string> so .has() accepts any string without
|
||||
// requiring `state as AgentStatusState` at the check site. The narrowing
|
||||
@@ -217,10 +219,10 @@ export const AGENT_TYPE_MAX_LENGTH = 40
|
||||
// sequence. Shared by the single-line and multiline normalizers so the
|
||||
// protection can't drift between them.
|
||||
function truncatePreservingSurrogates(value: string, maxLength: number): string {
|
||||
if (value.length <= maxLength) {
|
||||
if (value.length < maxLength) {
|
||||
return value
|
||||
}
|
||||
let truncated = value.slice(0, maxLength)
|
||||
let truncated = value.length === maxLength ? value : value.slice(0, maxLength)
|
||||
const lastCode = truncated.charCodeAt(truncated.length - 1)
|
||||
if (lastCode >= 0xd800 && lastCode <= 0xdbff) {
|
||||
truncated = truncated.slice(0, -1)
|
||||
@@ -233,12 +235,47 @@ function normalizeField(value: unknown, maxLength: number = AGENT_STATUS_MAX_FIE
|
||||
if (typeof value !== 'string') {
|
||||
return ''
|
||||
}
|
||||
// Why: include Unicode line separators (U+2028, U+2029) in the collapse
|
||||
// set. A hook payload like "claude rogue" would otherwise bypass the
|
||||
// single-line invariant that downstream UI and equality checks rely on —
|
||||
// the data comes from an untrusted agent process.
|
||||
const singleLine = value.trim().replace(/[\r\n\u2028\u2029]+/g, ' ')
|
||||
return truncatePreservingSurrogates(singleLine, maxLength)
|
||||
return normalizeSingleLinePreview(value, maxLength)
|
||||
}
|
||||
|
||||
function normalizeSingleLinePreview(value: string, maxLength: number): string {
|
||||
// Why: hook prompt/tool fields are previews. Bound the source scan before
|
||||
// folding line breaks so paste-sized status text cannot run a full regex
|
||||
// replacement just to keep a small dashboard label.
|
||||
const scanEnd = Math.min(
|
||||
value.length,
|
||||
maxLength * SINGLE_LINE_FIELD_SCAN_MULTIPLIER + SINGLE_LINE_FIELD_SCAN_OVERHEAD
|
||||
)
|
||||
let index = 0
|
||||
while (index < scanEnd && isEcmaTrimWhitespace(value.charCodeAt(index))) {
|
||||
index++
|
||||
}
|
||||
|
||||
let normalized = ''
|
||||
let lineSeparatorRun = false
|
||||
while (index < scanEnd && normalized.length < maxLength) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (isSingleLineSeparator(code)) {
|
||||
if (code === 13 && value.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
if (!lineSeparatorRun) {
|
||||
normalized += ' '
|
||||
}
|
||||
lineSeparatorRun = true
|
||||
index++
|
||||
continue
|
||||
}
|
||||
|
||||
normalized += value[index]
|
||||
lineSeparatorRun = false
|
||||
index++
|
||||
}
|
||||
|
||||
if (normalized.length < maxLength) {
|
||||
normalized = trimTrailingWhitespace(normalized)
|
||||
}
|
||||
return truncatePreservingSurrogates(normalized, maxLength)
|
||||
}
|
||||
|
||||
// Why: assistant messages are a multi-paragraph "what did the agent say"
|
||||
@@ -258,15 +295,68 @@ function normalizeMultilineField(value: unknown, maxLength: number): string {
|
||||
// normalizer's treatment of the same code points, keeping the two paths in
|
||||
// sync. Step order preserved: `\r\n` → `\n`, bare `\r` → `\n`,
|
||||
// U+2028/U+2029 → `\n`, then collapse blank-line runs.
|
||||
const normalized = value
|
||||
.trim()
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n')
|
||||
.replace(/[\u2028\u2029]/g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
const { start, end } = getTrimmedStringBounds(value)
|
||||
let normalized = ''
|
||||
let newlineRun = 0
|
||||
for (let index = start; index < end && normalized.length < maxLength; index++) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (code === 13 || code === 10 || code === 0x2028 || code === 0x2029) {
|
||||
if (code === 13 && value.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
if (newlineRun < 2) {
|
||||
normalized += '\n'
|
||||
}
|
||||
newlineRun++
|
||||
continue
|
||||
}
|
||||
|
||||
normalized += value[index]
|
||||
newlineRun = 0
|
||||
}
|
||||
return truncatePreservingSurrogates(normalized, maxLength)
|
||||
}
|
||||
|
||||
function getTrimmedStringBounds(value: string): { start: number; end: number } {
|
||||
let start = 0
|
||||
let end = value.length
|
||||
while (start < end && isEcmaTrimWhitespace(value.charCodeAt(start))) {
|
||||
start++
|
||||
}
|
||||
while (end > start && isEcmaTrimWhitespace(value.charCodeAt(end - 1))) {
|
||||
end--
|
||||
}
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
function trimTrailingWhitespace(value: string): string {
|
||||
let end = value.length
|
||||
while (end > 0 && isEcmaTrimWhitespace(value.charCodeAt(end - 1))) {
|
||||
end--
|
||||
}
|
||||
return end === value.length ? value : value.slice(0, end)
|
||||
}
|
||||
|
||||
function isSingleLineSeparator(code: number): boolean {
|
||||
return code === 13 || code === 10 || code === 0x2028 || code === 0x2029
|
||||
}
|
||||
|
||||
function isEcmaTrimWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 0x20 ||
|
||||
(code >= 0x09 && code <= 0x0d) ||
|
||||
code === 0xa0 ||
|
||||
code === 0x1680 ||
|
||||
(code >= 0x2000 && code <= 0x200a) ||
|
||||
code === 0x2028 ||
|
||||
code === 0x2029 ||
|
||||
code === 0x202f ||
|
||||
code === 0x205f ||
|
||||
code === 0x3000 ||
|
||||
code === 0xfeff
|
||||
)
|
||||
}
|
||||
|
||||
// Why: tool/assistant fields are optional on the entry (absence = "no update
|
||||
// for this field"). We only surface them when the caller actually provided a
|
||||
// string value so a missing field doesn't overwrite the prior cached state.
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { deriveGeneratedTabTitle, GENERATED_TAB_TITLE_MAX_LENGTH } from './agent-tab-title'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
deriveGeneratedTabTitle,
|
||||
GENERATED_TAB_TITLE_MAX_LENGTH,
|
||||
GENERATED_TAB_TITLE_SOURCE_SCAN_LIMIT
|
||||
} from './agent-tab-title'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('deriveGeneratedTabTitle', () => {
|
||||
it('derives a short title from the first useful prompt clause', () => {
|
||||
@@ -14,6 +22,12 @@ describe('deriveGeneratedTabTitle', () => {
|
||||
).toBe('Fix src auth')
|
||||
})
|
||||
|
||||
it('preserves non-ASCII title text while folding Unicode whitespace', () => {
|
||||
expect(deriveGeneratedTabTitle('Please 修正\u00a0résumé\t検索\u3000123!!!')).toBe(
|
||||
'修正 résumé 検索 123'
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps useful text after common issue prefixes', () => {
|
||||
expect(deriveGeneratedTabTitle('Issue #2056: Opt-in generated tab titles for agents')).toBe(
|
||||
'Opt in generated tab titles for agents'
|
||||
@@ -33,4 +47,28 @@ describe('deriveGeneratedTabTitle', () => {
|
||||
it('returns null when the prompt has no useful title text', () => {
|
||||
expect(deriveGeneratedTabTitle('please!!!')).toBeNull()
|
||||
})
|
||||
|
||||
it('bounds normalization work for paste-sized prompts before truncating the title', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const prompt = `Please fix \`src/auth.ts\` ${'large pasted text '.repeat(5000)}`
|
||||
|
||||
const title = deriveGeneratedTabTitle(prompt)
|
||||
|
||||
expect(title).toBeTruthy()
|
||||
expect(title!.length).toBeLessThanOrEqual(GENERATED_TAB_TITLE_MAX_LENGTH)
|
||||
const replaceContextLengths = replaceSpy.mock.contexts.map((context) => String(context).length)
|
||||
const splitContextLengths = splitSpy.mock.contexts.map((context) => String(context).length)
|
||||
expect(Math.max(...replaceContextLengths)).toBeLessThanOrEqual(
|
||||
GENERATED_TAB_TITLE_SOURCE_SCAN_LIMIT
|
||||
)
|
||||
expect(Math.max(...splitContextLengths)).toBeLessThanOrEqual(
|
||||
GENERATED_TAB_TITLE_SOURCE_SCAN_LIMIT
|
||||
)
|
||||
expect(
|
||||
replaceSpy.mock.calls.filter(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+'
|
||||
)
|
||||
).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const GENERATED_TAB_TITLE_MAX_LENGTH = 40
|
||||
export const GENERATED_TAB_TITLE_SOURCE_SCAN_LIMIT = 512
|
||||
|
||||
const LEADING_FILLER_PATTERNS: RegExp[] = [
|
||||
/^(?:can|could|would)\s+you(?:\s+please)?\s+/i,
|
||||
@@ -31,8 +32,47 @@ function truncateAtWordBoundary(value: string, maxLength: number): string {
|
||||
return sliced
|
||||
}
|
||||
|
||||
// Why: generated titles are derived from pasted agent prompts on renderer
|
||||
// state paths; collapse display whitespace without a regex replacement pass.
|
||||
function foldGeneratedTabTitleWhitespace(value: string): string {
|
||||
let normalized = ''
|
||||
let pendingWhitespace = false
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (isGeneratedTabTitleWhitespace(code)) {
|
||||
pendingWhitespace = normalized.length > 0
|
||||
continue
|
||||
}
|
||||
if (pendingWhitespace) {
|
||||
normalized += ' '
|
||||
pendingWhitespace = false
|
||||
}
|
||||
normalized += value.charAt(index)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function isGeneratedTabTitleWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
|
||||
export function deriveGeneratedTabTitle(prompt: string): string | null {
|
||||
const firstClause = prompt
|
||||
// Why: agent prompts can be paste-sized. Generated tab titles are previews,
|
||||
// so title cleanup must not scan the full prompt on the renderer state path.
|
||||
const promptPreview = prompt.slice(0, GENERATED_TAB_TITLE_SOURCE_SCAN_LIMIT)
|
||||
const firstClause = promptPreview
|
||||
.trim()
|
||||
.replace(/[`*_~#>[\]{}()]/g, ' ')
|
||||
.replace(/^(?:issue|task|bug|feature|pr)\s*(?:#?\d+)?\s*[:-]\s*/i, '')
|
||||
@@ -56,10 +96,7 @@ export function deriveGeneratedTabTitle(prompt: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
candidate = candidate
|
||||
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
candidate = foldGeneratedTabTitleWhitespace(candidate.replace(/[^\p{L}\p{N}\s]/gu, ' '))
|
||||
|
||||
if (!candidate) {
|
||||
return null
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AUTOMATION_CRON_EXPRESSION_MAX_BYTES,
|
||||
buildAutomationCronSchedule,
|
||||
buildAutomationRrule,
|
||||
classifyAutomationCronSchedule,
|
||||
formatAutomationSchedule,
|
||||
getAutomationCronExpressionFields,
|
||||
isValidAutomationCronSchedule,
|
||||
isValidAutomationSchedule,
|
||||
latestAutomationOccurrenceAtOrBefore,
|
||||
@@ -21,6 +23,10 @@ function formatTimeForTest(hour: number, minute: number): string {
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('automation schedules', () => {
|
||||
it('uses the latest overdue hourly occurrence for missed-run grace decisions', () => {
|
||||
const rrule = buildAutomationRrule({ preset: 'hourly', hour: 9, minute: 0 })
|
||||
@@ -140,6 +146,28 @@ describe('automation schedules', () => {
|
||||
expect(formatAutomationSchedule('30 12 * * 7')).toBe(`Sundays at ${formatTimeForTest(12, 30)}`)
|
||||
})
|
||||
|
||||
it('tokenizes pasted cron whitespace without regex field splitting', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const schedule = ['15', String.fromCharCode(160), '10\n*\t*\rMON-FRI'].join('')
|
||||
|
||||
expect(getAutomationCronExpressionFields(schedule)).toEqual(['15', '10', '*', '*', 'MON-FRI'])
|
||||
expect(formatAutomationSchedule(schedule)).toBe(`Weekdays at ${formatTimeForTest(10, 15)}`)
|
||||
expect(
|
||||
split.mock.calls.filter(([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+')
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects oversized pasted cron expressions before field tokenization', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const oversizedSchedule = 'secret-cron-field '.repeat(AUTOMATION_CRON_EXPRESSION_MAX_BYTES)
|
||||
|
||||
expect(getAutomationCronExpressionFields(oversizedSchedule)).toEqual([])
|
||||
expect(isValidAutomationCronSchedule(oversizedSchedule)).toBe(false)
|
||||
expect(
|
||||
split.mock.calls.filter(([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+')
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('classifies simple cron schedules for provider edit flows', () => {
|
||||
expect(classifyAutomationCronSchedule('15 10 * * MON-FRI')).toMatchObject({
|
||||
kind: 'weekdays',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable max-lines -- Why: automation scheduling needs RRULE presets and
|
||||
* custom cron parsing to share one execution path for main/renderer parity. */
|
||||
import type { AutomationSchedulePreset } from './automations-types'
|
||||
import { isClipboardTextByteLengthOverLimit } from './clipboard-text'
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
const HOUR_MS = 60 * 60 * 1000
|
||||
@@ -8,6 +9,7 @@ const MINUTE_MS = 60 * 1000
|
||||
// Why: valid cron expressions like Feb 29 can have an 8-year gap across non-leap centuries.
|
||||
const CRON_SCAN_DAYS = 9 * 366
|
||||
const CRON_SCAN_MINUTES = CRON_SCAN_DAYS * 24 * 60
|
||||
export const AUTOMATION_CRON_EXPRESSION_MAX_BYTES = 2 * 1024
|
||||
|
||||
type ParsedRrule = {
|
||||
kind: 'rrule'
|
||||
@@ -177,7 +179,7 @@ function parseCronField(args: {
|
||||
}
|
||||
|
||||
function parseCronExpression(expression: string): ParsedCron {
|
||||
const parts = expression.trim().split(/\s+/)
|
||||
const parts = getAutomationCronExpressionFields(expression, 6)
|
||||
if (parts.length !== 5) {
|
||||
throw new Error('Cron schedule must have five fields.')
|
||||
}
|
||||
@@ -208,6 +210,47 @@ function parseCronExpression(expression: string): ParsedCron {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAutomationCronExpressionFields(expression: string, maxFields = 5): string[] {
|
||||
if (isClipboardTextByteLengthOverLimit(expression, AUTOMATION_CRON_EXPRESSION_MAX_BYTES)) {
|
||||
return []
|
||||
}
|
||||
const fields: string[] = []
|
||||
let tokenStart = -1
|
||||
for (let index = 0; index <= expression.length; index += 1) {
|
||||
const isEnd = index === expression.length
|
||||
if (!isEnd && !isAutomationCronFieldWhitespace(expression.charCodeAt(index))) {
|
||||
if (tokenStart === -1) {
|
||||
tokenStart = index
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (tokenStart !== -1) {
|
||||
fields.push(expression.slice(tokenStart, index))
|
||||
tokenStart = -1
|
||||
if (fields.length >= maxFields) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
function isAutomationCronFieldWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
|
||||
function parseSchedule(schedule: string): ParsedSchedule {
|
||||
const trimmed = schedule.trim()
|
||||
if (trimmed.includes('=')) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
CLIPBOARD_IMAGE_MAX_BASE64_CHARS,
|
||||
CLIPBOARD_IMAGE_MAX_PIXELS,
|
||||
CLIPBOARD_IMAGE_MAX_SOURCE_BYTES,
|
||||
assertClipboardImageBase64LengthWithinLimit,
|
||||
assertClipboardImageByteLengthWithinLimit,
|
||||
assertClipboardImageDimensionsWithinLimit
|
||||
} from './clipboard-image'
|
||||
|
||||
describe('clipboard image limits', () => {
|
||||
it('accepts image metadata within configured limits', () => {
|
||||
expect(() =>
|
||||
assertClipboardImageBase64LengthWithinLimit(CLIPBOARD_IMAGE_MAX_BASE64_CHARS)
|
||||
).not.toThrow()
|
||||
expect(() =>
|
||||
assertClipboardImageByteLengthWithinLimit(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES)
|
||||
).not.toThrow()
|
||||
expect(() => assertClipboardImageDimensionsWithinLimit({ height: 1, width: 1 })).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects oversized byte and base64 lengths with metadata-only errors', () => {
|
||||
expect(() =>
|
||||
assertClipboardImageBase64LengthWithinLimit(CLIPBOARD_IMAGE_MAX_BASE64_CHARS + 1)
|
||||
).toThrow('Clipboard image is too large')
|
||||
expect(() =>
|
||||
assertClipboardImageByteLengthWithinLimit(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1)
|
||||
).toThrow('Clipboard image is too large')
|
||||
})
|
||||
|
||||
it('rejects invalid or oversized image dimensions before pixel allocation', () => {
|
||||
expect(() =>
|
||||
assertClipboardImageDimensionsWithinLimit({
|
||||
height: 1,
|
||||
width: CLIPBOARD_IMAGE_MAX_PIXELS + 1
|
||||
})
|
||||
).toThrow('Clipboard image is too large')
|
||||
expect(() => assertClipboardImageDimensionsWithinLimit({ height: 0, width: 1 })).toThrow(
|
||||
'Clipboard image is too large'
|
||||
)
|
||||
expect(() =>
|
||||
assertClipboardImageDimensionsWithinLimit({ height: Number.POSITIVE_INFINITY, width: 1 })
|
||||
).toThrow('Clipboard image is too large')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
export const CLIPBOARD_IMAGE_MAX_BASE64_CHARS = 24 * 1024 * 1024
|
||||
export const CLIPBOARD_IMAGE_MAX_SOURCE_BYTES = Math.floor(
|
||||
(CLIPBOARD_IMAGE_MAX_BASE64_CHARS / 4) * 3
|
||||
)
|
||||
export const CLIPBOARD_IMAGE_MAX_PIXELS = 32 * 1024 * 1024
|
||||
export const CLIPBOARD_IMAGE_TOO_LARGE_ERROR = 'Clipboard image is too large'
|
||||
|
||||
export type ClipboardImageDimensions = {
|
||||
height: number
|
||||
width: number
|
||||
}
|
||||
|
||||
export function assertClipboardImageBase64LengthWithinLimit(length: number): void {
|
||||
if (!Number.isFinite(length) || length > CLIPBOARD_IMAGE_MAX_BASE64_CHARS) {
|
||||
throw new Error(CLIPBOARD_IMAGE_TOO_LARGE_ERROR)
|
||||
}
|
||||
}
|
||||
|
||||
export function assertClipboardImageByteLengthWithinLimit(byteLength: number): void {
|
||||
if (!Number.isFinite(byteLength) || byteLength > CLIPBOARD_IMAGE_MAX_SOURCE_BYTES) {
|
||||
throw new Error(CLIPBOARD_IMAGE_TOO_LARGE_ERROR)
|
||||
}
|
||||
}
|
||||
|
||||
export function assertClipboardImageDimensionsWithinLimit({
|
||||
height,
|
||||
width
|
||||
}: ClipboardImageDimensions): void {
|
||||
const pixelCount = width * height
|
||||
if (
|
||||
!Number.isFinite(pixelCount) ||
|
||||
width <= 0 ||
|
||||
height <= 0 ||
|
||||
pixelCount > CLIPBOARD_IMAGE_MAX_PIXELS
|
||||
) {
|
||||
throw new Error(CLIPBOARD_IMAGE_TOO_LARGE_ERROR)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS,
|
||||
CLIPBOARD_TEXT_TOO_LARGE_ERROR,
|
||||
CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR,
|
||||
assertClipboardTextWriteWithinLimit,
|
||||
assertClipboardTextWriteWithinLimitWithYield,
|
||||
assertClipboardTextWithinLimit,
|
||||
assertClipboardTextWithinLimitWithYield,
|
||||
getClipboardTextByteLength,
|
||||
isClipboardTextByteLengthOverLimit,
|
||||
isClipboardTextByteLengthOverLimitWithYield,
|
||||
isClipboardTextTooLargeError,
|
||||
isClipboardTextWriteTooLargeError,
|
||||
measureClipboardTextByteLength,
|
||||
measureClipboardTextByteLengthWithYield
|
||||
} from './clipboard-text'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('clipboard text limits', () => {
|
||||
it('measures UTF-8 bytes instead of UTF-16 code units', () => {
|
||||
expect(getClipboardTextByteLength('a😀')).toBe(5)
|
||||
})
|
||||
|
||||
it('can stop measuring once a byte limit is exceeded', () => {
|
||||
const measurement = measureClipboardTextByteLength('😀'.repeat(100), {
|
||||
stopAfterBytes: 5
|
||||
})
|
||||
|
||||
expect(measurement).toEqual({ byteLength: 8, exceededLimit: true })
|
||||
expect(measurement.byteLength).toBeLessThan(getClipboardTextByteLength('😀'.repeat(100)))
|
||||
})
|
||||
|
||||
it('detects text over a byte limit without requiring full measurement', () => {
|
||||
expect(isClipboardTextByteLengthOverLimit('😀'.repeat(100), 5)).toBe(true)
|
||||
expect(isClipboardTextByteLengthOverLimit('éé', 4)).toBe(false)
|
||||
})
|
||||
|
||||
it('yields while measuring large accepted clipboard text', async () => {
|
||||
const yieldToEventLoop = vi.fn(async () => {})
|
||||
|
||||
const measurement = await measureClipboardTextByteLengthWithYield('x'.repeat(32), {
|
||||
stopAfterBytes: 64,
|
||||
yieldAfterCodeUnits: 8,
|
||||
yieldToEventLoop
|
||||
})
|
||||
|
||||
expect(measurement).toEqual({ byteLength: 32, exceededLimit: false })
|
||||
expect(yieldToEventLoop).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses the default 256k code-unit yield cadence for accepted large clipboard text', async () => {
|
||||
const yieldToEventLoop = vi.fn(async () => {})
|
||||
|
||||
const measurement = await measureClipboardTextByteLengthWithYield(
|
||||
'x'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS * 2 + 1),
|
||||
{
|
||||
yieldToEventLoop
|
||||
}
|
||||
)
|
||||
|
||||
expect(measurement.exceededLimit).toBe(false)
|
||||
expect(yieldToEventLoop).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('yields while checking multibyte clipboard limits before rejecting', async () => {
|
||||
const yieldToEventLoop = vi.fn(async () => {})
|
||||
|
||||
await expect(
|
||||
isClipboardTextByteLengthOverLimitWithYield('é'.repeat(16), 31, {
|
||||
yieldAfterCodeUnits: 4,
|
||||
yieldToEventLoop
|
||||
})
|
||||
).resolves.toBe(true)
|
||||
|
||||
expect(yieldToEventLoop).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects text whose string length already exceeds the byte limit without scanning', () => {
|
||||
const codePointAt = vi.spyOn(String.prototype, 'codePointAt')
|
||||
|
||||
expect(isClipboardTextByteLengthOverLimit('x'.repeat(6), 5)).toBe(true)
|
||||
expect(() => assertClipboardTextWithinLimit('x'.repeat(6), { maxBytes: 5 })).toThrow(
|
||||
CLIPBOARD_TEXT_TOO_LARGE_ERROR
|
||||
)
|
||||
expect(() => assertClipboardTextWriteWithinLimit('x'.repeat(6), { maxBytes: 5 })).toThrow(
|
||||
CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
|
||||
)
|
||||
expect(codePointAt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets each clipboard consumer override the shared default byte limits', async () => {
|
||||
expect(assertClipboardTextWithinLimit('abc', { maxBytes: 3 })).toBe('abc')
|
||||
expect(() => assertClipboardTextWithinLimit('abc', { maxBytes: 2 })).toThrow(
|
||||
CLIPBOARD_TEXT_TOO_LARGE_ERROR
|
||||
)
|
||||
expect(assertClipboardTextWriteWithinLimit('copy', { maxBytes: 4 })).toBe('copy')
|
||||
expect(() => assertClipboardTextWriteWithinLimit('copy', { maxBytes: 3 })).toThrow(
|
||||
CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR
|
||||
)
|
||||
|
||||
await expect(assertClipboardTextWithinLimitWithYield('async', { maxBytes: 5 })).resolves.toBe(
|
||||
'async'
|
||||
)
|
||||
await expect(
|
||||
assertClipboardTextWriteWithinLimitWithYield('async', { maxBytes: 4 })
|
||||
).rejects.toThrow(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
})
|
||||
|
||||
it('rejects oversized text with a metadata-only error', () => {
|
||||
expect(() => assertClipboardTextWithinLimit('secret-token-value', { maxBytes: 4 })).toThrow(
|
||||
CLIPBOARD_TEXT_TOO_LARGE_ERROR
|
||||
)
|
||||
|
||||
try {
|
||||
assertClipboardTextWithinLimit('secret-token-value', { maxBytes: 4 })
|
||||
} catch (error) {
|
||||
expect(isClipboardTextTooLargeError(error)).toBe(true)
|
||||
expect(String(error)).not.toContain('secret-token-value')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects oversized async clipboard reads and writes with metadata-only errors', async () => {
|
||||
await expect(
|
||||
assertClipboardTextWithinLimitWithYield('secret-token-value', { maxBytes: 4 })
|
||||
).rejects.toThrow(CLIPBOARD_TEXT_TOO_LARGE_ERROR)
|
||||
await expect(
|
||||
assertClipboardTextWriteWithinLimitWithYield('copied-secret-token-value', { maxBytes: 4 })
|
||||
).rejects.toThrow(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
|
||||
try {
|
||||
await assertClipboardTextWithinLimitWithYield('secret-token-value', { maxBytes: 4 })
|
||||
} catch (error) {
|
||||
expect(isClipboardTextTooLargeError(error)).toBe(true)
|
||||
expect(String(error)).not.toContain('secret-token-value')
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects oversized clipboard writes with a metadata-only error', () => {
|
||||
expect(() =>
|
||||
assertClipboardTextWriteWithinLimit('copied-secret-token-value', { maxBytes: 4 })
|
||||
).toThrow(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
|
||||
try {
|
||||
assertClipboardTextWriteWithinLimit('copied-secret-token-value', { maxBytes: 4 })
|
||||
} catch (error) {
|
||||
expect(isClipboardTextWriteTooLargeError(error)).toBe(true)
|
||||
expect(isClipboardTextTooLargeError(error)).toBe(false)
|
||||
expect(String(error)).not.toContain('copied-secret-token-value')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
export const CLIPBOARD_TEXT_READ_MAX_BYTES = 16 * 1024 * 1024
|
||||
export const CLIPBOARD_TEXT_WRITE_MAX_BYTES = 16 * 1024 * 1024
|
||||
export const CLIPBOARD_TEXT_TOO_LARGE_ERROR = 'Clipboard text is too large for this paste target.'
|
||||
export const CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR = 'Clipboard text is too large to copy safely.'
|
||||
export const CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS = 256 * 1024
|
||||
|
||||
export type ReadClipboardTextOptions = {
|
||||
maxBytes?: number
|
||||
}
|
||||
|
||||
export type WriteClipboardTextOptions = {
|
||||
maxBytes?: number
|
||||
}
|
||||
|
||||
export type ClipboardTextByteLengthMeasurement = {
|
||||
byteLength: number
|
||||
exceededLimit: boolean
|
||||
}
|
||||
|
||||
export function measureClipboardTextByteLength(
|
||||
text: string,
|
||||
options: { stopAfterBytes?: number } = {}
|
||||
): ClipboardTextByteLengthMeasurement {
|
||||
const stopAfterBytes = options.stopAfterBytes
|
||||
let byteLength = 0
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const codePoint = text.codePointAt(index) ?? 0
|
||||
byteLength += getUtf8ByteLengthForCodePoint(codePoint)
|
||||
if (Number.isFinite(stopAfterBytes) && byteLength > (stopAfterBytes ?? 0)) {
|
||||
return { byteLength, exceededLimit: true }
|
||||
}
|
||||
if (codePoint > 0xffff) {
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
return { byteLength, exceededLimit: false }
|
||||
}
|
||||
|
||||
export function getClipboardTextByteLength(text: string): number {
|
||||
return measureClipboardTextByteLength(text).byteLength
|
||||
}
|
||||
|
||||
export async function measureClipboardTextByteLengthWithYield(
|
||||
text: string,
|
||||
options: {
|
||||
stopAfterBytes?: number
|
||||
yieldAfterCodeUnits?: number
|
||||
yieldToEventLoop?: () => Promise<void>
|
||||
} = {}
|
||||
): Promise<ClipboardTextByteLengthMeasurement> {
|
||||
const stopAfterBytes = options.stopAfterBytes
|
||||
const yieldAfterCodeUnits = Math.max(
|
||||
1,
|
||||
options.yieldAfterCodeUnits ?? CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS
|
||||
)
|
||||
const yieldToEventLoop = options.yieldToEventLoop ?? defaultClipboardTextMeasureYield
|
||||
let nextYieldAt = yieldAfterCodeUnits
|
||||
let byteLength = 0
|
||||
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const codePoint = text.codePointAt(index) ?? 0
|
||||
byteLength += getUtf8ByteLengthForCodePoint(codePoint)
|
||||
if (Number.isFinite(stopAfterBytes) && byteLength > (stopAfterBytes ?? 0)) {
|
||||
return { byteLength, exceededLimit: true }
|
||||
}
|
||||
if (codePoint > 0xffff) {
|
||||
index += 1
|
||||
}
|
||||
if (index >= nextYieldAt) {
|
||||
await yieldToEventLoop()
|
||||
nextYieldAt = index + yieldAfterCodeUnits
|
||||
}
|
||||
}
|
||||
return { byteLength, exceededLimit: false }
|
||||
}
|
||||
|
||||
export function isClipboardTextByteLengthOverLimit(text: string, maxBytes: number): boolean {
|
||||
return (
|
||||
text.length > maxBytes ||
|
||||
measureClipboardTextByteLength(text, { stopAfterBytes: maxBytes }).exceededLimit
|
||||
)
|
||||
}
|
||||
|
||||
export async function isClipboardTextByteLengthOverLimitWithYield(
|
||||
text: string,
|
||||
maxBytes: number,
|
||||
options: {
|
||||
yieldAfterCodeUnits?: number
|
||||
yieldToEventLoop?: () => Promise<void>
|
||||
} = {}
|
||||
): Promise<boolean> {
|
||||
if (text.length > maxBytes) {
|
||||
return true
|
||||
}
|
||||
return (
|
||||
await measureClipboardTextByteLengthWithYield(text, {
|
||||
stopAfterBytes: maxBytes,
|
||||
yieldAfterCodeUnits: options.yieldAfterCodeUnits,
|
||||
yieldToEventLoop: options.yieldToEventLoop
|
||||
})
|
||||
).exceededLimit
|
||||
}
|
||||
|
||||
export function getClipboardTextReadMaxBytes(
|
||||
options: ReadClipboardTextOptions | undefined,
|
||||
fallback = CLIPBOARD_TEXT_READ_MAX_BYTES
|
||||
): number {
|
||||
return Number.isFinite(options?.maxBytes) && (options?.maxBytes ?? 0) > 0
|
||||
? Math.floor(options?.maxBytes ?? fallback)
|
||||
: fallback
|
||||
}
|
||||
|
||||
export function getClipboardTextWriteMaxBytes(
|
||||
options: WriteClipboardTextOptions | undefined,
|
||||
fallback = CLIPBOARD_TEXT_WRITE_MAX_BYTES
|
||||
): number {
|
||||
return Number.isFinite(options?.maxBytes) && (options?.maxBytes ?? 0) > 0
|
||||
? Math.floor(options?.maxBytes ?? fallback)
|
||||
: fallback
|
||||
}
|
||||
|
||||
export function assertClipboardTextWithinLimit(
|
||||
text: string,
|
||||
options?: ReadClipboardTextOptions
|
||||
): string {
|
||||
const maxBytes = getClipboardTextReadMaxBytes(options)
|
||||
if (isClipboardTextByteLengthOverLimit(text, maxBytes)) {
|
||||
throw new Error(CLIPBOARD_TEXT_TOO_LARGE_ERROR)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export async function assertClipboardTextWithinLimitWithYield(
|
||||
text: string,
|
||||
options?: ReadClipboardTextOptions
|
||||
): Promise<string> {
|
||||
const maxBytes = getClipboardTextReadMaxBytes(options)
|
||||
if (await isClipboardTextByteLengthOverLimitWithYield(text, maxBytes)) {
|
||||
throw new Error(CLIPBOARD_TEXT_TOO_LARGE_ERROR)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export function assertClipboardTextWriteWithinLimit(
|
||||
text: string,
|
||||
options?: WriteClipboardTextOptions
|
||||
): string {
|
||||
const maxBytes = getClipboardTextWriteMaxBytes(options)
|
||||
if (isClipboardTextByteLengthOverLimit(text, maxBytes)) {
|
||||
throw new Error(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export async function assertClipboardTextWriteWithinLimitWithYield(
|
||||
text: string,
|
||||
options?: WriteClipboardTextOptions
|
||||
): Promise<string> {
|
||||
const maxBytes = getClipboardTextWriteMaxBytes(options)
|
||||
if (await isClipboardTextByteLengthOverLimitWithYield(text, maxBytes)) {
|
||||
throw new Error(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export function isClipboardTextTooLargeError(error: unknown): boolean {
|
||||
return error instanceof Error && error.message.includes(CLIPBOARD_TEXT_TOO_LARGE_ERROR)
|
||||
}
|
||||
|
||||
export function isClipboardTextWriteTooLargeError(error: unknown): boolean {
|
||||
return error instanceof Error && error.message.includes(CLIPBOARD_TEXT_WRITE_TOO_LARGE_ERROR)
|
||||
}
|
||||
|
||||
function getUtf8ByteLengthForCodePoint(codePoint: number): number {
|
||||
if (codePoint <= 0x7f) {
|
||||
return 1
|
||||
}
|
||||
if (codePoint <= 0x7ff) {
|
||||
return 2
|
||||
}
|
||||
if (codePoint <= 0xffff) {
|
||||
return 3
|
||||
}
|
||||
return 4
|
||||
}
|
||||
|
||||
function defaultClipboardTextMeasureYield(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { extractCodexAuthError, isCodexAuthError } from './codex-auth-errors'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('isCodexAuthError', () => {
|
||||
it('matches Codex authentication refresh failures', () => {
|
||||
expect(isCodexAuthError('Access token could not be refreshed')).toBe(true)
|
||||
expect(isCodexAuthError('plain provider error')).toBe(false)
|
||||
expect(isCodexAuthError(null)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractCodexAuthError', () => {
|
||||
it('returns the first matching auth line', () => {
|
||||
expect(
|
||||
extractCodexAuthError('startup log\nERROR: not logged in. Please sign in again.\nmore log')
|
||||
).toBe('ERROR: not logged in. Please sign in again.')
|
||||
})
|
||||
|
||||
it('strips ANSI color from matching lines', () => {
|
||||
expect(extractCodexAuthError('\u001b[31mnot logged in\u001b[0m\n')).toBe('not logged in')
|
||||
})
|
||||
|
||||
it('scans newline-heavy output without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const output = `${'startup log\r\n'.repeat(10_000)}please reauthenticate\r\n`
|
||||
|
||||
expect(extractCodexAuthError(output)).toBe('please reauthenticate')
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -20,18 +20,45 @@ export function isCodexAuthError(error: string | null | undefined): boolean {
|
||||
}
|
||||
|
||||
export function extractCodexAuthError(output: string | null | undefined): string | null {
|
||||
const cleanOutput = output?.replace(ANSI_ESCAPE_RE, '').trim()
|
||||
if (!cleanOutput) {
|
||||
if (!output) {
|
||||
return null
|
||||
}
|
||||
|
||||
const matchingLine = cleanOutput
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.find(isCodexAuthError)
|
||||
if (matchingLine) {
|
||||
return matchingLine
|
||||
let cleanPrefix = ''
|
||||
for (const rawLine of iterateCodexOutputLines(output)) {
|
||||
const line = rawLine.replace(ANSI_ESCAPE_RE, '').trim()
|
||||
if (!line) {
|
||||
continue
|
||||
}
|
||||
if (isCodexAuthError(line)) {
|
||||
return line.slice(0, 4_000)
|
||||
}
|
||||
if (cleanPrefix.length < 4_000) {
|
||||
cleanPrefix = cleanPrefix ? `${cleanPrefix}\n${line}` : line
|
||||
cleanPrefix = cleanPrefix.slice(0, 4_000)
|
||||
}
|
||||
}
|
||||
|
||||
return isCodexAuthError(cleanOutput) ? cleanOutput.slice(0, 4_000) : null
|
||||
return isCodexAuthError(cleanPrefix) ? cleanPrefix : null
|
||||
}
|
||||
|
||||
function* iterateCodexOutputLines(output: string): Generator<string> {
|
||||
let lineStart = 0
|
||||
|
||||
for (let index = 0; index < output.length; index++) {
|
||||
const code = output.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield output.slice(lineStart, index)
|
||||
if (code === 13 && output.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
lineStart = index + 1
|
||||
}
|
||||
|
||||
if (lineStart <= output.length) {
|
||||
yield output.slice(lineStart)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
COMMAND_TOKEN_SCAN_MAX_CHARS,
|
||||
commandContainsToken,
|
||||
getCommandTokenPathBasename,
|
||||
getFirstCommandToken
|
||||
} from './command-token-scanner'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function getRegexWhitespaceSplitCalls(split: ReturnType<typeof vi.spyOn>): unknown[][] {
|
||||
return split.mock.calls.filter(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+'
|
||||
)
|
||||
}
|
||||
|
||||
describe('command token scanner', () => {
|
||||
it('extracts a first command token across pasted whitespace without regex splitting', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const command = [' ', String.fromCharCode(160), 'codex\t--resume'].join('')
|
||||
|
||||
expect(getFirstCommandToken(command)).toBe('codex')
|
||||
expect(getRegexWhitespaceSplitCalls(split)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('preserves quoted command paths with spaces', () => {
|
||||
expect(getFirstCommandToken('"C:\\Program Files\\Orca\\codex.cmd" --resume')).toBe(
|
||||
'C:\\Program Files\\Orca\\codex.cmd'
|
||||
)
|
||||
})
|
||||
|
||||
it('extracts path basenames without allocating path segment arrays', () => {
|
||||
expect(getCommandTokenPathBasename('C:\\Program Files\\Orca\\codex.cmd')).toBe('codex.cmd')
|
||||
expect(getCommandTokenPathBasename('/usr/local/bin/omp')).toBe('omp')
|
||||
})
|
||||
|
||||
it('bounds pathological single-token commands', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const command = 'a'.repeat(COMMAND_TOKEN_SCAN_MAX_CHARS + 100)
|
||||
|
||||
expect(getFirstCommandToken(command)).toHaveLength(COMMAND_TOKEN_SCAN_MAX_CHARS)
|
||||
expect(getRegexWhitespaceSplitCalls(split)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('finds exact command tokens without regex splitting', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const command = '/Applications/serve-sim/bin/serve-sim-bin\tUDID-1 --port 3100'
|
||||
|
||||
expect(commandContainsToken(command, 'UDID-1')).toBe(true)
|
||||
expect(commandContainsToken(command, 'UDID')).toBe(false)
|
||||
expect(getRegexWhitespaceSplitCalls(split)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
// Why: command strings may include pasted scripts; first-token classification must stay bounded.
|
||||
export const COMMAND_TOKEN_SCAN_MAX_CHARS = 4096
|
||||
|
||||
export function getFirstCommandToken(command: string): string {
|
||||
const scanLimit = Math.min(command.length, COMMAND_TOKEN_SCAN_MAX_CHARS)
|
||||
let index = 0
|
||||
|
||||
while (index < scanLimit && isCommandTokenWhitespace(command.charCodeAt(index))) {
|
||||
index += 1
|
||||
}
|
||||
if (index >= scanLimit) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const quote = command[index]
|
||||
if ((quote === '"' || quote === "'") && index + 1 < scanLimit) {
|
||||
const tokenStart = index + 1
|
||||
for (let end = tokenStart; end < scanLimit; end += 1) {
|
||||
if (command[end] === quote) {
|
||||
if (end > tokenStart) {
|
||||
return command.slice(tokenStart, end)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const tokenStart = index
|
||||
while (index < scanLimit && !isCommandTokenWhitespace(command.charCodeAt(index))) {
|
||||
index += 1
|
||||
}
|
||||
return command.slice(tokenStart, index)
|
||||
}
|
||||
|
||||
export function getCommandTokenPathBasename(token: string): string {
|
||||
for (let index = token.length - 1; index >= 0; index -= 1) {
|
||||
const code = token.charCodeAt(index)
|
||||
if (code === 47 || code === 92) {
|
||||
return token.slice(index + 1)
|
||||
}
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
export function commandContainsToken(command: string, expectedToken: string): boolean {
|
||||
if (!expectedToken) {
|
||||
return false
|
||||
}
|
||||
|
||||
const scanLimit = Math.min(command.length, COMMAND_TOKEN_SCAN_MAX_CHARS)
|
||||
let index = 0
|
||||
|
||||
while (index < scanLimit) {
|
||||
while (index < scanLimit && isCommandTokenWhitespace(command.charCodeAt(index))) {
|
||||
index += 1
|
||||
}
|
||||
const tokenStart = index
|
||||
while (index < scanLimit && !isCommandTokenWhitespace(command.charCodeAt(index))) {
|
||||
index += 1
|
||||
}
|
||||
if (tokenStart < index && command.slice(tokenStart, index) === expectedToken) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function isCommandTokenWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
/** Strips noise around the agent's output: surrounding whitespace, a single
|
||||
* enclosing fenced code block, and lone "Generating…" preamble lines some
|
||||
* CLIs print before the real answer. */
|
||||
export function cleanGeneratedCommitMessage(raw: string): string {
|
||||
// Why: agent output can include very large generated bodies; normalize and
|
||||
// unwrap by scanning boundaries instead of building newline-sized arrays.
|
||||
let text = normalizeGeneratedCommitMessageLineFeeds(raw).trim()
|
||||
|
||||
// Why: real commit messages never start with an ellipsis or the word
|
||||
// "Generating"/"Thinking" — those leak from CLIs that print a status line
|
||||
// before the actual response.
|
||||
const firstNewline = text.indexOf('\n')
|
||||
if (firstNewline !== -1) {
|
||||
const firstLine = text.slice(0, firstNewline)
|
||||
if (/^(generating|thinking)\b/i.test(firstLine) || /^[.…]+$/.test(firstLine.trim())) {
|
||||
text = text.slice(firstNewline + 1).trim()
|
||||
}
|
||||
}
|
||||
|
||||
const fenced = findEnclosingCommitMessageFenceBody(text)
|
||||
if (fenced !== null) {
|
||||
text = fenced.trim()
|
||||
}
|
||||
|
||||
// Why: some CLIs format a one-shot answer as a list item even when the
|
||||
// prompt asks for raw text; a Git subject should not carry that marker.
|
||||
text = text.replace(/^(\s*)(?:[-*•●]\s+|\d+[.)]\s+)/, '$1').trim()
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
function normalizeGeneratedCommitMessageLineFeeds(value: string): string {
|
||||
let crlfStart = value.indexOf('\r\n')
|
||||
if (crlfStart === -1) {
|
||||
return value
|
||||
}
|
||||
|
||||
let normalized = value.slice(0, crlfStart)
|
||||
let chunkStart = crlfStart + 2
|
||||
normalized += '\n'
|
||||
crlfStart = value.indexOf('\r\n', chunkStart)
|
||||
|
||||
while (crlfStart !== -1) {
|
||||
normalized += value.slice(chunkStart, crlfStart)
|
||||
normalized += '\n'
|
||||
chunkStart = crlfStart + 2
|
||||
crlfStart = value.indexOf('\r\n', chunkStart)
|
||||
}
|
||||
|
||||
return `${normalized}${value.slice(chunkStart)}`
|
||||
}
|
||||
|
||||
function findEnclosingCommitMessageFenceBody(text: string): string | null {
|
||||
if (!text.startsWith('```')) {
|
||||
return null
|
||||
}
|
||||
|
||||
let headerEnd = 3
|
||||
while (headerEnd < text.length && text.charCodeAt(headerEnd) !== 10) {
|
||||
if (!isCommitFenceInfoCharacter(text.charCodeAt(headerEnd))) {
|
||||
return null
|
||||
}
|
||||
headerEnd++
|
||||
}
|
||||
|
||||
if (headerEnd >= text.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const closingFenceStart = text.length - 3
|
||||
if (closingFenceStart <= headerEnd || !text.endsWith('```')) {
|
||||
return null
|
||||
}
|
||||
if (text.charCodeAt(closingFenceStart - 1) !== 10) {
|
||||
return null
|
||||
}
|
||||
|
||||
return text.slice(headerEnd + 1, closingFenceStart - 1)
|
||||
}
|
||||
|
||||
function isCommitFenceInfoCharacter(code: number): boolean {
|
||||
return (
|
||||
(code >= 48 && code <= 57) ||
|
||||
(code >= 65 && code <= 90) ||
|
||||
(code >= 97 && code <= 122) ||
|
||||
code === 45 ||
|
||||
code === 95
|
||||
)
|
||||
}
|
||||
|
||||
function stripAnsiControlSequences(value: string): string {
|
||||
return value.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, 'g'), '')
|
||||
}
|
||||
|
||||
const AGENT_ERROR_CODE_SCAN_LIMIT = 8192
|
||||
const ERROR_CODE_MARKER = 'error code:'
|
||||
|
||||
// Why: agent CLIs (Codex, Claude) prefix their stdout/stderr with config
|
||||
// preamble, the echoed prompt, and hook lifecycle messages. When something
|
||||
// fails, the actionable error is buried far below all of that. This pulls
|
||||
// out the real message so the user sees something legible instead of a
|
||||
// dump of the agent's runtime state.
|
||||
export function extractAgentErrorMessage(stdout: string, stderr: string): string | null {
|
||||
const combined = `${stdout}\n${stderr}`
|
||||
// Pass 1: look for an `ERROR:`/`Error:` line carrying a JSON payload.
|
||||
// Walk from the end so the most recent (and usually most meaningful)
|
||||
// error wins when an agent prints multiple.
|
||||
const errorPayload = findLastAgentErrorPayload(combined)
|
||||
if (errorPayload !== null) {
|
||||
const payload = errorPayload.trim()
|
||||
if (payload.startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as {
|
||||
message?: string
|
||||
error?: { message?: string }
|
||||
}
|
||||
const inner = parsed.error?.message ?? parsed.message
|
||||
if (typeof inner === 'string' && inner.trim().length > 0) {
|
||||
return inner.trim()
|
||||
}
|
||||
} catch {
|
||||
// Fall through to using the raw payload below.
|
||||
}
|
||||
}
|
||||
if (payload.length > 0) {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
const compact = extractCompactedErrorCodeTail(combined)
|
||||
const errorCodeMatch = compact ? /\bError code:\s*\d+\s*-\s*(.+)$/i.exec(compact) : null
|
||||
if (errorCodeMatch) {
|
||||
const payload = errorCodeMatch[1].trim()
|
||||
const messageMatch = /['"]message['"]\s*:\s*['"]([^'"]+)['"]/i.exec(payload)
|
||||
if (messageMatch?.[1]?.trim()) {
|
||||
return messageMatch[1].trim()
|
||||
}
|
||||
if (payload.length > 0) {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function extractCompactedErrorCodeTail(combined: string): string | null {
|
||||
const markerStart = lastIndexOfAsciiIgnoreCase(combined, ERROR_CODE_MARKER)
|
||||
if (markerStart === -1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return compactAgentErrorTail(
|
||||
combined.slice(markerStart, markerStart + AGENT_ERROR_CODE_SCAN_LIMIT)
|
||||
)
|
||||
}
|
||||
|
||||
function lastIndexOfAsciiIgnoreCase(value: string, needle: string): number {
|
||||
if (needle.length === 0 || value.length < needle.length) {
|
||||
return -1
|
||||
}
|
||||
for (let index = value.length - needle.length; index >= 0; index -= 1) {
|
||||
if (equalsAsciiIgnoreCaseAt(value, needle, index)) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function equalsAsciiIgnoreCaseAt(value: string, needle: string, index: number): boolean {
|
||||
for (let offset = 0; offset < needle.length; offset += 1) {
|
||||
if (
|
||||
toAsciiLowerCode(value.charCodeAt(index + offset)) !==
|
||||
toAsciiLowerCode(needle.charCodeAt(offset))
|
||||
) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function compactAgentErrorTail(value: string): string {
|
||||
let compact = ''
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (code === 13 || code === 10) {
|
||||
if (code === 13 && value.charCodeAt(index + 1) === 10) {
|
||||
index += 1
|
||||
}
|
||||
const next = findNextNonWhitespaceCode(value, index + 1)
|
||||
if (shouldDropWrappedLineBreak(compact.charCodeAt(compact.length - 1), next)) {
|
||||
index = next.index - 1
|
||||
continue
|
||||
}
|
||||
if (compact.length > 0 && compact.charCodeAt(compact.length - 1) !== 32) {
|
||||
compact += ' '
|
||||
}
|
||||
index = next.index - 1
|
||||
continue
|
||||
}
|
||||
if (isAsciiWhitespace(code)) {
|
||||
if (compact.length > 0 && compact.charCodeAt(compact.length - 1) !== 32) {
|
||||
compact += ' '
|
||||
}
|
||||
continue
|
||||
}
|
||||
compact += value[index]
|
||||
}
|
||||
return compact.trim()
|
||||
}
|
||||
|
||||
function findNextNonWhitespaceCode(value: string, start: number): { code: number; index: number } {
|
||||
for (let index = start; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (!isAsciiWhitespace(code)) {
|
||||
return { code, index }
|
||||
}
|
||||
}
|
||||
return { code: Number.NaN, index: value.length }
|
||||
}
|
||||
|
||||
function shouldDropWrappedLineBreak(previous: number, next: { code: number }): boolean {
|
||||
return isAsciiLetter(previous) && (isAsciiLetter(next.code) || next.code === 95)
|
||||
}
|
||||
|
||||
function isAsciiWhitespace(code: number): boolean {
|
||||
return code === 9 || code === 10 || code === 11 || code === 12 || code === 13 || code === 32
|
||||
}
|
||||
|
||||
function isAsciiLetter(code: number): boolean {
|
||||
const lower = toAsciiLowerCode(code)
|
||||
return lower >= 97 && lower <= 122
|
||||
}
|
||||
|
||||
function toAsciiLowerCode(code: number): number {
|
||||
return code >= 65 && code <= 90 ? code + 32 : code
|
||||
}
|
||||
|
||||
function findLastAgentErrorPayload(combined: string): string | null {
|
||||
let lineEnd = combined.length
|
||||
|
||||
for (let index = combined.length - 1; index >= -1; index--) {
|
||||
if (index >= 0) {
|
||||
const code = combined.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
if (code === 10 && index > 0 && combined.charCodeAt(index - 1) === 13) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Why: agent logs can include paste-sized echoed prompts. Error lines are
|
||||
// short diagnostics, so bound per-line ANSI stripping before matching.
|
||||
const rawLine = combined.slice(
|
||||
index + 1,
|
||||
Math.min(lineEnd, index + 1 + AGENT_ERROR_CODE_SCAN_LIMIT)
|
||||
)
|
||||
const line = rawLine.includes(String.fromCharCode(27))
|
||||
? stripAnsiControlSequences(rawLine)
|
||||
: rawLine
|
||||
const match = /^\s*(?:ERROR|Error(?:\s+during\s+[^:]+)?)\s*:\s*(.+)$/i.exec(line)
|
||||
if (match?.[1]) {
|
||||
return match[1]
|
||||
}
|
||||
lineEnd = index > 0 && combined.charCodeAt(index - 1) === 13 ? index - 1 : index
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
COMMIT_MESSAGE_AGENT_SPECS,
|
||||
CUSTOM_AGENT_ID,
|
||||
@@ -18,6 +18,10 @@ import {
|
||||
resolveCommitMessageAgentChoice
|
||||
} from './commit-message-agent-spec'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('COMMIT_MESSAGE_AGENT_SPECS', () => {
|
||||
it('exposes the installed local agents as commit-message agents', () => {
|
||||
const ids = listCommitMessageAgentIds().sort()
|
||||
@@ -290,6 +294,57 @@ describe('model discovery parsers', () => {
|
||||
{ id: 'GPT-OSS 120B (Medium)', label: 'GPT-OSS 120B (Medium)' }
|
||||
])
|
||||
})
|
||||
|
||||
it('parses CRLF-heavy dynamic model outputs without full line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const noise = 'ignored model with spaces\r\n'.repeat(10_000)
|
||||
const blankNoise = '\r\n'.repeat(10_000)
|
||||
|
||||
expect(parseLineModels(`${noise}opencode/gpt-5.4-mini\r\nopenai/gpt-5.5\r\n`)).toEqual([
|
||||
{
|
||||
id: 'opencode/gpt-5.4-mini',
|
||||
label: 'Opencode GPT 5.4 Mini',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'openai/gpt-5.5',
|
||||
label: 'Openai GPT 5.5',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
}
|
||||
])
|
||||
expect(
|
||||
parsePiModels(
|
||||
`${noise}provider model context max-out thinking images\r\ngithub-copilot gpt-5.4-mini 400K 128K yes yes\r\n`
|
||||
)[0]?.id
|
||||
).toBe('github-copilot/gpt-5.4-mini')
|
||||
expect(parseCursorModels(`${noise}auto - Auto\r\ngpt-5.2 - GPT-5.2\r\n`)).toHaveLength(2)
|
||||
expect(parseAntigravityModels(`${blankNoise}Gemini 3.5 Flash (Medium)\r\n`)).toEqual([
|
||||
{ id: 'Gemini 3.5 Flash (Medium)', label: 'Gemini 3.5 Flash (Medium)' }
|
||||
])
|
||||
|
||||
const usedFullLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
const usedWhitespaceFieldSplit = splitSpy.mock.calls.some(
|
||||
([separator]) => separator instanceof RegExp && separator.source === '\\s+'
|
||||
)
|
||||
expect(usedFullLineSplit).toBe(false)
|
||||
expect(usedWhitespaceFieldSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildArgs (Codex)', () => {
|
||||
|
||||
@@ -104,6 +104,27 @@ function uniqueModels(models: CommitMessageModel[]): CommitMessageModel[] {
|
||||
})
|
||||
}
|
||||
|
||||
function* iterateModelOutputLines(output: string): Generator<string> {
|
||||
let lineStart = 0
|
||||
|
||||
for (let index = 0; index < output.length; index++) {
|
||||
const code = output.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield output.slice(lineStart, index)
|
||||
if (code === 13 && output.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
lineStart = index + 1
|
||||
}
|
||||
|
||||
if (lineStart <= output.length) {
|
||||
yield output.slice(lineStart)
|
||||
}
|
||||
}
|
||||
|
||||
function withOpenAiThinking(
|
||||
id: string
|
||||
): Pick<CommitMessageModel, 'thinkingLevels' | 'defaultThinkingLevel'> {
|
||||
@@ -148,74 +169,121 @@ export function parseCodexModels(stdout: string): CommitMessageModel[] {
|
||||
}
|
||||
|
||||
export function parseLineModels(stdout: string): CommitMessageModel[] {
|
||||
return uniqueModels(
|
||||
stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.includes(' '))
|
||||
.map((id) => ({
|
||||
id,
|
||||
label: labelFromModelId(id),
|
||||
...withOpenAiThinking(id)
|
||||
}))
|
||||
)
|
||||
const models: CommitMessageModel[] = []
|
||||
for (const rawLine of iterateModelOutputLines(stdout)) {
|
||||
const id = rawLine.trim()
|
||||
if (id.length === 0 || id.includes(' ')) {
|
||||
continue
|
||||
}
|
||||
models.push({
|
||||
id,
|
||||
label: labelFromModelId(id),
|
||||
...withOpenAiThinking(id)
|
||||
})
|
||||
}
|
||||
return uniqueModels(models)
|
||||
}
|
||||
|
||||
export function parsePiModels(stdout: string): CommitMessageModel[] {
|
||||
return uniqueModels(
|
||||
stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim().split(/\s+/))
|
||||
.filter((parts) => parts.length >= 6 && parts[0] !== 'provider')
|
||||
.map((parts) => {
|
||||
const [provider, model, , , thinking] = parts
|
||||
const id = `${provider}/${model}`
|
||||
return {
|
||||
id,
|
||||
label: `${labelFromModelId(provider)} ${labelFromModelId(model)}`,
|
||||
...(thinking === 'yes'
|
||||
? {
|
||||
thinkingLevels: [
|
||||
{ id: 'off', label: 'Off' },
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
}
|
||||
: {})
|
||||
}
|
||||
})
|
||||
const models: CommitMessageModel[] = []
|
||||
for (const rawLine of iterateModelOutputLines(stdout)) {
|
||||
const parts = getPiModelTableFields(rawLine, 6)
|
||||
if (parts.length < 6 || parts[0] === 'provider') {
|
||||
continue
|
||||
}
|
||||
|
||||
const [provider, model, , , thinking] = parts
|
||||
const id = `${provider}/${model}`
|
||||
models.push({
|
||||
id,
|
||||
label: `${labelFromModelId(provider)} ${labelFromModelId(model)}`,
|
||||
...(thinking === 'yes'
|
||||
? {
|
||||
thinkingLevels: [
|
||||
{ id: 'off', label: 'Off' },
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
}
|
||||
: {})
|
||||
})
|
||||
}
|
||||
return uniqueModels(models)
|
||||
}
|
||||
|
||||
// Why: model discovery output can include paste-sized noisy lines; only the first fields matter.
|
||||
function getPiModelTableFields(line: string, maxFields: number): string[] {
|
||||
const fields: string[] = []
|
||||
let tokenStart = -1
|
||||
|
||||
for (let index = 0; index <= line.length; index += 1) {
|
||||
const isEnd = index === line.length
|
||||
if (!isEnd && !isPiModelTableWhitespace(line.charCodeAt(index))) {
|
||||
if (tokenStart === -1) {
|
||||
tokenStart = index
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (tokenStart !== -1) {
|
||||
fields.push(line.slice(tokenStart, index))
|
||||
tokenStart = -1
|
||||
if (fields.length >= maxFields) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
function isPiModelTableWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
|
||||
export function parseCursorModels(stdout: string): CommitMessageModel[] {
|
||||
return uniqueModels(
|
||||
stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.map((line) => /^([^\s]+)\s+-\s+(.+)$/.exec(line))
|
||||
.filter((match): match is RegExpExecArray => Boolean(match))
|
||||
.map((match) => ({
|
||||
id: match[1],
|
||||
label: match[2].replace(/\s+\((?:default|current)\)$/i, ''),
|
||||
...withOpenAiThinking(match[1])
|
||||
}))
|
||||
)
|
||||
const models: CommitMessageModel[] = []
|
||||
for (const rawLine of iterateModelOutputLines(stdout)) {
|
||||
const match = /^([^\s]+)\s+-\s+(.+)$/.exec(rawLine.trim())
|
||||
if (!match) {
|
||||
continue
|
||||
}
|
||||
models.push({
|
||||
id: match[1],
|
||||
label: match[2].replace(/\s+\((?:default|current)\)$/i, ''),
|
||||
...withOpenAiThinking(match[1])
|
||||
})
|
||||
}
|
||||
return uniqueModels(models)
|
||||
}
|
||||
|
||||
export function parseAntigravityModels(stdout: string): CommitMessageModel[] {
|
||||
return uniqueModels(
|
||||
stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((id) => ({
|
||||
id,
|
||||
label: id
|
||||
}))
|
||||
)
|
||||
const models: CommitMessageModel[] = []
|
||||
for (const rawLine of iterateModelOutputLines(stdout)) {
|
||||
const id = rawLine.trim()
|
||||
if (id.length === 0) {
|
||||
continue
|
||||
}
|
||||
models.push({
|
||||
id,
|
||||
label: id
|
||||
})
|
||||
}
|
||||
return uniqueModels(models)
|
||||
}
|
||||
|
||||
export const COMMIT_MESSAGE_AGENT_SPECS: Partial<Record<TuiAgent, CommitMessageAgentSpec>> = {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildCommitMessagePrompt, splitGeneratedCommitMessage } from './commit-message-generation'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('buildCommitMessagePrompt', () => {
|
||||
it('builds a prompt from staged context instead of asking the agent to inspect git', () => {
|
||||
const prompt = buildCommitMessagePrompt(
|
||||
@@ -61,4 +65,19 @@ describe('splitGeneratedCommitMessage', () => {
|
||||
message: 'Fix source control generation\n\n- Move planning into main'
|
||||
})
|
||||
})
|
||||
|
||||
it('extracts subject and body from newline-heavy output without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const body = '- Explain one generated change\n'.repeat(10_000).trimEnd()
|
||||
|
||||
const result = splitGeneratedCommitMessage(`Add generated paste protection\n\n${body}`)
|
||||
|
||||
expect(result.subject).toBe('Add generated paste protection')
|
||||
expect(result.body.startsWith('- Explain one generated change\n')).toBe(true)
|
||||
expect(result.body.endsWith('- Explain one generated change')).toBe(true)
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) => typeof separator === 'string' && separator === '\n'
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -71,9 +71,10 @@ export function buildCommitMessagePrompt(
|
||||
|
||||
export function splitGeneratedCommitMessage(message: string): GeneratedCommitMessage {
|
||||
const normalized = cleanGeneratedCommitMessage(message)
|
||||
const [subjectLine = '', ...bodyLines] = normalized.split('\n')
|
||||
const firstNewline = normalized.indexOf('\n')
|
||||
const subjectLine = firstNewline === -1 ? normalized : normalized.slice(0, firstNewline)
|
||||
const subject = subjectLine.trim().replace(/[.]+$/g, '').slice(0, 72).trimEnd()
|
||||
const body = bodyLines.join('\n').trim()
|
||||
const body = firstNewline === -1 ? '' : normalized.slice(firstNewline + 1).trim()
|
||||
const safeSubject = subject.length > 0 ? subject : 'Update project files'
|
||||
return {
|
||||
subject: safeSubject,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildCommitPrompt,
|
||||
cleanGeneratedCommitMessage,
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
truncateDiffForPrompt
|
||||
} from './commit-message-prompt'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('buildCommitPrompt', () => {
|
||||
it('embeds the diff into the base prompt', () => {
|
||||
const prompt = buildCommitPrompt('diff --git a/foo b/foo\n+hello', '')
|
||||
@@ -99,6 +103,27 @@ describe('cleanGeneratedCommitMessage', () => {
|
||||
expect(cleanGeneratedCommitMessage('feat: a\r\nbody line\r\n')).toBe('feat: a\nbody line')
|
||||
})
|
||||
|
||||
it('cleans large fenced CRLF output without regex-wide normalization', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const matchSpy = vi.spyOn(String.prototype, 'match')
|
||||
const fence = '```'
|
||||
const raw = `\r\n${fence}text\r\nfeat: large output\r\n${'body line\r\n'.repeat(10_000)}${fence}\r\n`
|
||||
|
||||
const result = cleanGeneratedCommitMessage(raw)
|
||||
|
||||
expect(result.startsWith('feat: large output\nbody line')).toBe(true)
|
||||
expect(result.endsWith('body line')).toBe(true)
|
||||
expect(result).not.toContain('\r\n')
|
||||
const usedCrlfReplace = replaceSpy.mock.calls.some(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\r\\n'
|
||||
)
|
||||
const usedFenceMatch = matchSpy.mock.calls.some(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source.includes('[\\s\\S]')
|
||||
)
|
||||
expect(usedCrlfReplace).toBe(false)
|
||||
expect(usedFenceMatch).toBe(false)
|
||||
})
|
||||
|
||||
it('strips a leading list marker from the commit subject', () => {
|
||||
expect(cleanGeneratedCommitMessage('● Add Copilot entry to agent results')).toBe(
|
||||
'Add Copilot entry to agent results'
|
||||
@@ -140,6 +165,18 @@ describe('extractAgentErrorMessage', () => {
|
||||
expect(extractAgentErrorMessage(out, '')).toBe('second failure')
|
||||
})
|
||||
|
||||
it('uses the last ERROR line in large CRLF output without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const out = `${'preamble\r\n'.repeat(10_000)}ERROR: first failure\r\nretry\r\nERROR: second failure\r\n`
|
||||
|
||||
expect(extractAgentErrorMessage(out, '')).toBe('second failure')
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) => separator instanceof RegExp && separator.source === '\\r?\\n'
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
|
||||
it('matches an `Error:` line emitted on stdout', () => {
|
||||
expect(extractAgentErrorMessage('Error: model unavailable\n', '')).toBe('model unavailable')
|
||||
})
|
||||
@@ -170,6 +207,30 @@ describe('extractAgentErrorMessage', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('extracts wrapped provider error-code payloads from large output without replacement passes', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const echoedPrompt = 'echoed pasted prompt '.repeat(10_000)
|
||||
const stdout = [
|
||||
`${echoedPrompt}Error code: 401 - {'error': {'message': 'The API Key appears to be invalid or ma`,
|
||||
"y have expired. Please verify your credentials and try again.', 'type': 'invalid",
|
||||
"_authentication_error'}}"
|
||||
].join('\r\n')
|
||||
|
||||
expect(extractAgentErrorMessage(stdout, '')).toBe(
|
||||
'The API Key appears to be invalid or may have expired. Please verify your credentials and try again.'
|
||||
)
|
||||
expect(replaceSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not strip ANSI across a paste-sized single-line log before error-code fallback', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const pastedLog = 'x'.repeat(20_000)
|
||||
const stdout = `${pastedLog}Error code: 400 - {'message': 'bad request'}`
|
||||
|
||||
expect(extractAgentErrorMessage(stdout, '')).toBe('bad request')
|
||||
expect(replaceSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns null when no ERROR line is present', () => {
|
||||
expect(extractAgentErrorMessage('plain log\nmore log\n', '')).toBeNull()
|
||||
})
|
||||
|
||||
@@ -17,6 +17,11 @@ Staged diff:
|
||||
\`\`\`
|
||||
`
|
||||
|
||||
export {
|
||||
cleanGeneratedCommitMessage,
|
||||
extractAgentErrorMessage
|
||||
} from './commit-message-agent-output'
|
||||
|
||||
/** Builds the final prompt sent to the agent. The custom suffix is appended verbatim
|
||||
* when non-empty so the user can override style (Conventional Commits, gitmoji, …). */
|
||||
export function buildCommitPrompt(diff: string, customSuffix: string): string {
|
||||
@@ -124,40 +129,6 @@ export function truncateDiffForPrompt(
|
||||
return sections.map((section, i) => clipSectionOnLineBoundary(section, allocations[i])).join('')
|
||||
}
|
||||
|
||||
/** Strips noise around the agent's output: surrounding whitespace, a single
|
||||
* enclosing fenced code block, and lone "Generating…" preamble lines some
|
||||
* CLIs print before the real answer. */
|
||||
export function cleanGeneratedCommitMessage(raw: string): string {
|
||||
let text = raw.replace(/\r\n/g, '\n').trim()
|
||||
|
||||
// Why: real commit messages never start with an ellipsis or the word
|
||||
// "Generating"/"Thinking" — those leak from CLIs that print a status line
|
||||
// before the actual response.
|
||||
const firstNewline = text.indexOf('\n')
|
||||
if (firstNewline !== -1) {
|
||||
const firstLine = text.slice(0, firstNewline)
|
||||
if (/^(generating|thinking)\b/i.test(firstLine) || /^[.…]+$/.test(firstLine.trim())) {
|
||||
text = text.slice(firstNewline + 1).trim()
|
||||
}
|
||||
}
|
||||
|
||||
const fence = /^```[a-zA-Z0-9_-]*\n([\s\S]*?)\n```$/
|
||||
const fenced = text.match(fence)
|
||||
if (fenced) {
|
||||
text = fenced[1].trim()
|
||||
}
|
||||
|
||||
// Why: some CLIs format a one-shot answer as a list item even when the
|
||||
// prompt asks for raw text; a Git subject should not carry that marker.
|
||||
text = text.replace(/^(\s*)(?:[-*•●]\s+|\d+[.)]\s+)/, '$1').trim()
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
function stripAnsiControlSequences(value: string): string {
|
||||
return value.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, 'g'), '')
|
||||
}
|
||||
|
||||
export const CUSTOM_PROMPT_PLACEHOLDER = '{prompt}'
|
||||
|
||||
export type TokenizeCustomCommandResult =
|
||||
@@ -277,57 +248,3 @@ export function planCustomCommand(template: string, prompt: string): CustomComma
|
||||
}
|
||||
return { ok: true, binary, args: rest, stdinPayload: prompt }
|
||||
}
|
||||
|
||||
// Why: agent CLIs (Codex, Claude) prefix their stdout/stderr with config
|
||||
// preamble, the echoed prompt, and hook lifecycle messages. When something
|
||||
// fails, the actionable error is buried far below all of that. This pulls
|
||||
// out the real message so the user sees something legible instead of a
|
||||
// dump of the agent's runtime state.
|
||||
export function extractAgentErrorMessage(stdout: string, stderr: string): string | null {
|
||||
const combined = stripAnsiControlSequences(`${stdout}\n${stderr}`)
|
||||
const lines = combined.split(/\r?\n/)
|
||||
|
||||
// Pass 1: look for an `ERROR:`/`Error:` line carrying a JSON payload.
|
||||
// Walk from the end so the most recent (and usually most meaningful)
|
||||
// error wins when an agent prints multiple.
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i]
|
||||
const match = /^\s*(?:ERROR|Error(?:\s+during\s+[^:]+)?)\s*:\s*(.+)$/i.exec(line)
|
||||
if (!match) {
|
||||
continue
|
||||
}
|
||||
const payload = match[1].trim()
|
||||
if (payload.startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as {
|
||||
message?: string
|
||||
error?: { message?: string }
|
||||
}
|
||||
const inner = parsed.error?.message ?? parsed.message
|
||||
if (typeof inner === 'string' && inner.trim().length > 0) {
|
||||
return inner.trim()
|
||||
}
|
||||
} catch {
|
||||
// Fall through to using the raw payload below.
|
||||
}
|
||||
}
|
||||
if (payload.length > 0) {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
const compact = combined.replace(/([A-Za-z])\r?\n\s*([A-Za-z_])/g, '$1$2').replace(/\s+/g, ' ')
|
||||
const errorCodeMatch = /\bError code:\s*\d+\s*-\s*(.+)$/i.exec(compact)
|
||||
if (errorCodeMatch) {
|
||||
const payload = errorCodeMatch[1].trim()
|
||||
const messageMatch = /['"]message['"]\s*:\s*['"]([^'"]+)['"]/i.exec(payload)
|
||||
if (messageMatch?.[1]?.trim()) {
|
||||
return messageMatch[1].trim()
|
||||
}
|
||||
if (payload.length > 0) {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getGitCloneFailureMessage } from './git-clone-failure-message'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('getGitCloneFailureMessage', () => {
|
||||
it('turns an existing destination into an actionable message after progress output', () => {
|
||||
expect(
|
||||
@@ -41,4 +45,18 @@ describe('getGitCloneFailureMessage', () => {
|
||||
'network vanished'
|
||||
)
|
||||
})
|
||||
|
||||
it('summarizes CRLF-heavy stderr without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const stderr = `${'remote: counting objects\r\n'.repeat(10_000)}fatal: repository not found\r\n`
|
||||
|
||||
expect(getGitCloneFailureMessage(stderr)).toBe('fatal: repository not found')
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,14 +2,14 @@ export function getGitCloneFailureMessage(
|
||||
stderr: string,
|
||||
options: { clonePath?: string | null } = {}
|
||||
): string {
|
||||
const lines = stderr
|
||||
.replace(/\r/g, '\n')
|
||||
.split('\n')
|
||||
.map((line) => stripAnsi(line).trim())
|
||||
.filter(Boolean)
|
||||
let fallbackLine: string | null = null
|
||||
|
||||
for (let index = lines.length - 1; index >= 0; index--) {
|
||||
const line = lines[index]
|
||||
for (const rawLine of iterateLinesFromEnd(stderr)) {
|
||||
const line = stripAnsi(rawLine).trim()
|
||||
if (!line) {
|
||||
continue
|
||||
}
|
||||
fallbackLine ??= line
|
||||
const fatalIndex = line.indexOf('fatal:')
|
||||
if (fatalIndex !== -1) {
|
||||
return formatGitCloneFailureLine(line.slice(fatalIndex), options)
|
||||
@@ -20,7 +20,28 @@ export function getGitCloneFailureMessage(
|
||||
}
|
||||
}
|
||||
|
||||
return formatGitCloneFailureLine(lines.at(-1) ?? 'unknown error', options)
|
||||
return formatGitCloneFailureLine(fallbackLine ?? 'unknown error', options)
|
||||
}
|
||||
|
||||
function* iterateLinesFromEnd(value: string): Generator<string> {
|
||||
let lineEnd = value.length
|
||||
let index = value.length - 1
|
||||
|
||||
while (index >= 0) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
index--
|
||||
continue
|
||||
}
|
||||
|
||||
const delimiterStart =
|
||||
code === 10 && index > 0 && value.charCodeAt(index - 1) === 13 ? index - 1 : index
|
||||
yield value.slice(index + 1, lineEnd)
|
||||
lineEnd = delimiterStart
|
||||
index = delimiterStart - 1
|
||||
}
|
||||
|
||||
yield value.slice(0, lineEnd)
|
||||
}
|
||||
|
||||
function stripAnsi(value: string): string {
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
hasConfiguredBranchPushTarget
|
||||
} from './git-configured-branch-target'
|
||||
import { splitRemoteBranchName } from './git-remote-branch-name'
|
||||
import { parseGitRevListAheadBehindCounts } from './git-rev-list-output'
|
||||
import { iterateProcessOutputLines } from './process-output-field-scanner'
|
||||
|
||||
export { gitRefTargetsBranchName, splitRemoteBranchName } from './git-remote-branch-name'
|
||||
|
||||
@@ -34,22 +36,25 @@ async function splitRemoteBranchNameByKnownRemote(
|
||||
): Promise<{ remoteName: string; branchName: string } | null> {
|
||||
try {
|
||||
const { stdout } = await runGit(['remote'])
|
||||
const remotes = stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.length - a.length)
|
||||
return (
|
||||
remotes
|
||||
.map((remoteName) => {
|
||||
if (refName === remoteName || !refName.startsWith(`${remoteName}/`)) {
|
||||
return null
|
||||
}
|
||||
const branchName = refName.slice(remoteName.length + 1)
|
||||
return branchName ? { remoteName, branchName } : null
|
||||
})
|
||||
.find((parsed) => parsed !== null) ?? null
|
||||
)
|
||||
let bestRemoteName: string | null = null
|
||||
for (const rawLine of iterateProcessOutputLines(stdout)) {
|
||||
const remoteName = rawLine.trim()
|
||||
// Why: preserve longest-remote matching for remote names that contain slashes.
|
||||
if (
|
||||
!remoteName ||
|
||||
refName === remoteName ||
|
||||
!refName.startsWith(`${remoteName}/`) ||
|
||||
(bestRemoteName && bestRemoteName.length >= remoteName.length)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
bestRemoteName = remoteName
|
||||
}
|
||||
if (!bestRemoteName) {
|
||||
return null
|
||||
}
|
||||
const branchName = refName.slice(bestRemoteName.length + 1)
|
||||
return branchName ? { remoteName: bestRemoteName, branchName } : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -207,27 +212,24 @@ export async function getEffectiveGitUpstreamStatus(
|
||||
'--count',
|
||||
`HEAD...${upstream.upstreamName}`
|
||||
])
|
||||
const tokens = stdout.trim().split(/\s+/)
|
||||
if (tokens.length !== 2) {
|
||||
const counts = parseGitRevListAheadBehindCounts(stdout)
|
||||
if (counts.status === 'unexpected-field-count') {
|
||||
throw new Error(`Unexpected git rev-list output: ${JSON.stringify(stdout)}`)
|
||||
}
|
||||
|
||||
const ahead = Number.parseInt(tokens[0]!, 10)
|
||||
const behind = Number.parseInt(tokens[1]!, 10)
|
||||
if (!Number.isFinite(ahead) || !Number.isFinite(behind) || ahead < 0 || behind < 0) {
|
||||
if (counts.status === 'unparseable-counts') {
|
||||
throw new Error(`Unparseable git rev-list counts: ${JSON.stringify(stdout)}`)
|
||||
}
|
||||
|
||||
const behindCommitsArePatchEquivalent =
|
||||
ahead > 0 && behind > 0 && getBehindCommitsArePatchEquivalent
|
||||
counts.ahead > 0 && counts.behind > 0 && getBehindCommitsArePatchEquivalent
|
||||
? await getBehindCommitsArePatchEquivalent(upstream.upstreamName)
|
||||
: undefined
|
||||
|
||||
return {
|
||||
hasUpstream: true,
|
||||
upstreamName: upstream.upstreamName,
|
||||
ahead,
|
||||
behind,
|
||||
ahead: counts.ahead,
|
||||
behind: counts.behind,
|
||||
...(behindCommitsArePatchEquivalent !== undefined ? { behindCommitsArePatchEquivalent } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
syncForkDefaultBranch,
|
||||
validateGitForkSyncExpectedUpstream,
|
||||
type GitForkSyncRunner
|
||||
} from './git-fork-sync'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function createRunner(overrides: {
|
||||
remotes?: string
|
||||
upstreamUrl?: string
|
||||
@@ -101,6 +105,29 @@ describe('syncForkDefaultBranch', () => {
|
||||
expect(flattenedCommands(calls)).not.toContain('push origin')
|
||||
})
|
||||
|
||||
it('scans newline-heavy remote and default-branch output without line-array splitting', async () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const { runGit } = createRunner({
|
||||
remotes: `${'\r\n'.repeat(10_000)}origin\r\nupstream\r\n`,
|
||||
defaultBranchOutput: `${'metadata\r\n'.repeat(
|
||||
10_000
|
||||
)}ref: refs/heads/main\tHEAD\r\n0123456789012345678901234567890123456789\tHEAD\r\n`,
|
||||
aheadBehind: '0\t0\n'
|
||||
})
|
||||
|
||||
await expect(syncForkDefaultBranch(runGit)).resolves.toMatchObject({
|
||||
status: 'up-to-date',
|
||||
branchName: 'main'
|
||||
})
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
|
||||
it('blocks when the fork has commits that are not upstream', async () => {
|
||||
const { runGit, calls } = createRunner({ aheadBehind: '2\t4\n' })
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { getProcessOutputFields } from './process-output-field-scanner'
|
||||
|
||||
export type ForkSyncMode = 'ask' | 'safe-auto' | 'off'
|
||||
|
||||
export type GitForkSyncBlockedReason =
|
||||
@@ -31,7 +33,7 @@ const DEFAULT_BRANCH_FALLBACKS = ['main', 'master']
|
||||
const GITHUB_HOSTS = new Set(['github.com', 'ssh.github.com'])
|
||||
|
||||
function parseRemoteHeadBranch(stdout: string): string | null {
|
||||
for (const line of stdout.split(/\r?\n/)) {
|
||||
for (const line of iterateGitOutputLines(stdout)) {
|
||||
const match = /^ref:\s+refs\/heads\/(.+?)\s+HEAD$/.exec(line.trim())
|
||||
if (match?.[1]) {
|
||||
return match[1]
|
||||
@@ -41,7 +43,7 @@ function parseRemoteHeadBranch(stdout: string): string | null {
|
||||
}
|
||||
|
||||
function parseAheadBehind(stdout: string): { ahead: number; behind: number } {
|
||||
const [aheadRaw, behindRaw] = stdout.trim().split(/\s+/, 2)
|
||||
const [aheadRaw, behindRaw] = getProcessOutputFields(stdout, 2)
|
||||
return {
|
||||
ahead: Number.parseInt(aheadRaw ?? '0', 10) || 0,
|
||||
behind: Number.parseInt(behindRaw ?? '0', 10) || 0
|
||||
@@ -50,10 +52,33 @@ function parseAheadBehind(stdout: string): { ahead: number; behind: number } {
|
||||
|
||||
async function remoteExists(runGit: GitForkSyncRunner, remote: string): Promise<boolean> {
|
||||
const { stdout } = await runGit(['remote'])
|
||||
return stdout
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.includes(remote)
|
||||
for (const rawLine of iterateGitOutputLines(stdout)) {
|
||||
if (rawLine.trim() === remote) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function* iterateGitOutputLines(output: string): Generator<string> {
|
||||
let lineStart = 0
|
||||
|
||||
for (let index = 0; index < output.length; index++) {
|
||||
const code = output.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield output.slice(lineStart, index)
|
||||
if (code === 13 && output.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
lineStart = index + 1
|
||||
}
|
||||
|
||||
if (lineStart <= output.length) {
|
||||
yield output.slice(lineStart)
|
||||
}
|
||||
}
|
||||
|
||||
function cleanGitHubRemotePath(path: string): string | null {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { GitUpstreamStatus } from './git-status-types'
|
||||
import type { GitPushTarget } from './types'
|
||||
import { parseGitRevListAheadBehindCounts } from './git-rev-list-output'
|
||||
|
||||
export type GitCommandRunner = (args: string[]) => Promise<{ stdout: string }>
|
||||
|
||||
@@ -47,27 +48,24 @@ export async function getPublishTargetStatus(
|
||||
}
|
||||
|
||||
const { stdout } = await runGit(['rev-list', '--left-right', '--count', `HEAD...${remoteRef}`])
|
||||
const tokens = stdout.trim().split(/\s+/)
|
||||
if (tokens.length !== 2) {
|
||||
const counts = parseGitRevListAheadBehindCounts(stdout)
|
||||
if (counts.status === 'unexpected-field-count') {
|
||||
throw new Error(`Unexpected git rev-list output: ${JSON.stringify(stdout)}`)
|
||||
}
|
||||
|
||||
const ahead = Number.parseInt(tokens[0]!, 10)
|
||||
const behind = Number.parseInt(tokens[1]!, 10)
|
||||
if (!Number.isFinite(ahead) || !Number.isFinite(behind) || ahead < 0 || behind < 0) {
|
||||
if (counts.status === 'unparseable-counts') {
|
||||
throw new Error(`Unparseable git rev-list counts: ${JSON.stringify(stdout)}`)
|
||||
}
|
||||
|
||||
const behindCommitsArePatchEquivalent =
|
||||
ahead > 0 && behind > 0 && getBehindCommitsArePatchEquivalent
|
||||
counts.ahead > 0 && counts.behind > 0 && getBehindCommitsArePatchEquivalent
|
||||
? await getBehindCommitsArePatchEquivalent(remoteRef)
|
||||
: undefined
|
||||
|
||||
return {
|
||||
hasUpstream: true,
|
||||
upstreamName,
|
||||
ahead,
|
||||
behind,
|
||||
ahead: counts.ahead,
|
||||
behind: counts.behind,
|
||||
...(behindCommitsArePatchEquivalent !== undefined ? { behindCommitsArePatchEquivalent } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
formatSubmodulePushFailureDetail,
|
||||
isNoUpstreamError,
|
||||
normalizeGitErrorMessage
|
||||
} from './git-remote-error'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('normalizeGitErrorMessage', () => {
|
||||
it('keeps the submodule name when a recursive push is rejected', () => {
|
||||
const error = new Error(
|
||||
@@ -33,6 +37,22 @@ describe('normalizeGitErrorMessage', () => {
|
||||
'git config pull.rebase true (rebase), or git config pull.ff only (fast-forward only).'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the tail diagnostic from newline-heavy failures without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const error = new Error(
|
||||
`Command failed: git fetch\r\n${'remote: progress update\r\n'.repeat(10_000)}remote side closed connection\r\n`
|
||||
)
|
||||
|
||||
expect(normalizeGitErrorMessage(error, 'fetch')).toBe('remote side closed connection')
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSubmodulePushFailureDetail', () => {
|
||||
@@ -55,6 +75,20 @@ describe('formatSubmodulePushFailureDetail', () => {
|
||||
"Submodule 'vendor/tools' could not be pushed. Resolve the submodule push error, then try again."
|
||||
)
|
||||
})
|
||||
|
||||
it('checks newline-heavy output without full CRLF normalization', () => {
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const message = `${'remote: progress\r\n'.repeat(10_000)}Unable to push submodule 'vendor/tools'\r\nfatal: failed to push all needed submodules\r\n`
|
||||
|
||||
expect(formatSubmodulePushFailureDetail(message)).toBe(
|
||||
"Submodule 'vendor/tools' could not be pushed. Resolve the submodule push error, then try again."
|
||||
)
|
||||
|
||||
const usedCrlfReplace = replaceSpy.mock.calls.some(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\r\\n'
|
||||
)
|
||||
expect(usedCrlfReplace).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNoUpstreamError', () => {
|
||||
|
||||
@@ -25,20 +25,20 @@ export function stripCredentialsFromMessage(message: string): string {
|
||||
|
||||
export function formatSubmodulePushFailureDetail(message: string): string | null {
|
||||
const raw = stripCredentialsFromMessage(message)
|
||||
const normalized = raw.replace(/\r\n/g, '\n').trim()
|
||||
const normalizedMatch = normalized.match(NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN)
|
||||
const trimmed = raw.trim()
|
||||
const normalizedMatch = trimmed.match(NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN)
|
||||
if (normalizedMatch) {
|
||||
return normalizedMatch[1]
|
||||
}
|
||||
if (!SUBMODULE_PUSH_FAILURE_SENTINEL_PATTERN.test(normalized)) {
|
||||
if (!SUBMODULE_PUSH_FAILURE_SENTINEL_PATTERN.test(trimmed)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: recursive push can hide the actionable nested rejection behind a
|
||||
// top-level "failed to push all needed submodules" fatal line.
|
||||
const submoduleName = normalized.match(SUBMODULE_PUSH_FAILURE_PATTERN)?.[1]?.trim()
|
||||
const submoduleName = trimmed.match(SUBMODULE_PUSH_FAILURE_PATTERN)?.[1]?.trim()
|
||||
const subject = submoduleName ? `Submodule '${submoduleName}'` : 'A submodule'
|
||||
if (SUBMODULE_REMOTE_CHANGED_PATTERN.test(normalized)) {
|
||||
if (SUBMODULE_REMOTE_CHANGED_PATTERN.test(trimmed)) {
|
||||
return `${subject} has remote changes. Pull inside the submodule, then try again.`
|
||||
}
|
||||
return `${subject} could not be pushed. Resolve the submodule push error, then try again.`
|
||||
@@ -49,11 +49,34 @@ function extractTailLine(message: string): string {
|
||||
// followed by the full stderr. The meaningful diagnostic is typically the
|
||||
// last non-empty line; surfacing the full blob risks leaking local paths or
|
||||
// environment details to the UI.
|
||||
const lines = message
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
return lines.at(-1) ?? message
|
||||
for (const rawLine of iterateLinesFromEnd(message)) {
|
||||
const line = rawLine.trim()
|
||||
if (line.length > 0) {
|
||||
return line
|
||||
}
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
function* iterateLinesFromEnd(value: string): Generator<string> {
|
||||
let lineEnd = value.length
|
||||
let index = value.length - 1
|
||||
|
||||
while (index >= 0) {
|
||||
const code = value.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
index--
|
||||
continue
|
||||
}
|
||||
|
||||
const delimiterStart =
|
||||
code === 10 && index > 0 && value.charCodeAt(index - 1) === 13 ? index - 1 : index
|
||||
yield value.slice(index + 1, lineEnd)
|
||||
lineEnd = delimiterStart
|
||||
index = delimiterStart - 1
|
||||
}
|
||||
|
||||
yield value.slice(0, lineEnd)
|
||||
}
|
||||
|
||||
export type GitRemoteOperation = 'push' | 'pull' | 'fetch' | 'upstream'
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
parseGitRevListAheadBehindCounts,
|
||||
parseGitRevListFirstParentOid
|
||||
} from './git-rev-list-output'
|
||||
|
||||
describe('parseGitRevListAheadBehindCounts', () => {
|
||||
it('parses rev-list counts without whitespace-regex splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
try {
|
||||
expect(parseGitRevListAheadBehindCounts(' 12\t3\r\n')).toEqual({
|
||||
status: 'ok',
|
||||
ahead: 12,
|
||||
behind: 3
|
||||
})
|
||||
const usedWhitespaceSplit = splitSpy.mock.calls.some(
|
||||
([separator]) => separator instanceof RegExp && separator.source === '\\s+'
|
||||
)
|
||||
expect(usedWhitespaceSplit).toBe(false)
|
||||
} finally {
|
||||
splitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects missing or extra fields', () => {
|
||||
expect(parseGitRevListAheadBehindCounts('1\n')).toEqual({
|
||||
status: 'unexpected-field-count'
|
||||
})
|
||||
expect(parseGitRevListAheadBehindCounts('1 2 3\n')).toEqual({
|
||||
status: 'unexpected-field-count'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unparseable counts', () => {
|
||||
expect(parseGitRevListAheadBehindCounts('1 nope\n')).toEqual({
|
||||
status: 'unparseable-counts'
|
||||
})
|
||||
expect(parseGitRevListAheadBehindCounts('-1 2\n')).toEqual({
|
||||
status: 'unparseable-counts'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGitRevListFirstParentOid', () => {
|
||||
it('returns the first parent from rev-list parent output', () => {
|
||||
expect(parseGitRevListFirstParentOid('commit-oid parent-oid second-parent\n')).toBe(
|
||||
'parent-oid'
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for a root commit', () => {
|
||||
expect(parseGitRevListFirstParentOid('commit-oid\n')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { getProcessOutputFields } from './process-output-field-scanner'
|
||||
|
||||
export type GitRevListAheadBehindCounts = {
|
||||
ahead: number
|
||||
behind: number
|
||||
}
|
||||
|
||||
export type GitRevListAheadBehindParseResult =
|
||||
| ({ status: 'ok' } & GitRevListAheadBehindCounts)
|
||||
| { status: 'unexpected-field-count' }
|
||||
| { status: 'unparseable-counts' }
|
||||
|
||||
export function parseGitRevListAheadBehindCounts(output: string): GitRevListAheadBehindParseResult {
|
||||
// Why: these Git outputs sit on status/paste-adjacent hot paths; scan only needed fields.
|
||||
const fields = getProcessOutputFields(output, 3)
|
||||
if (fields.length !== 2) {
|
||||
return { status: 'unexpected-field-count' }
|
||||
}
|
||||
|
||||
const ahead = parseGitRevListNonNegativeCount(fields[0])
|
||||
const behind = parseGitRevListNonNegativeCount(fields[1])
|
||||
if (ahead === null || behind === null) {
|
||||
return { status: 'unparseable-counts' }
|
||||
}
|
||||
|
||||
return { status: 'ok', ahead, behind }
|
||||
}
|
||||
|
||||
export function parseGitRevListFirstParentOid(output: string): string | null {
|
||||
return getProcessOutputFields(output, 2)[1] ?? null
|
||||
}
|
||||
|
||||
function parseGitRevListNonNegativeCount(value: string | undefined): number | null {
|
||||
if (!value || !/^\d+$/.test(value)) {
|
||||
return null
|
||||
}
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
return Number.isSafeInteger(parsed) ? parsed : null
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
shouldForcePushWithLeaseForUpstream,
|
||||
upstreamOnlyCommitsArePatchEquivalent
|
||||
} from './git-upstream-status'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('upstreamOnlyCommitsArePatchEquivalent', () => {
|
||||
it('returns true when every upstream-only commit is patch-equivalent', () => {
|
||||
expect(upstreamOnlyCommitsArePatchEquivalent('= abc\n= def\n')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for empty output or non-equivalent commits', () => {
|
||||
expect(upstreamOnlyCommitsArePatchEquivalent('')).toBe(false)
|
||||
expect(upstreamOnlyCommitsArePatchEquivalent('= abc\n+ def\n')).toBe(false)
|
||||
})
|
||||
|
||||
it('scans newline-heavy cherry output without line-array splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
const output = `${'\r\n'.repeat(10_000)}= abc\r\n= def\r\n`
|
||||
|
||||
expect(upstreamOnlyCommitsArePatchEquivalent(output)).toBe(true)
|
||||
|
||||
const usedLineSplit = splitSpy.mock.calls.some(
|
||||
([separator]) =>
|
||||
(typeof separator === 'string' && separator === '\n') ||
|
||||
(separator instanceof RegExp && separator.source === '\\r?\\n')
|
||||
)
|
||||
expect(usedLineSplit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldForcePushWithLeaseForUpstream', () => {
|
||||
it('requires a diverged upstream with patch-equivalent behind commits', () => {
|
||||
expect(
|
||||
shouldForcePushWithLeaseForUpstream({
|
||||
hasUpstream: true,
|
||||
ahead: 1,
|
||||
behind: 1,
|
||||
behindCommitsArePatchEquivalent: true
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
shouldForcePushWithLeaseForUpstream({
|
||||
hasUpstream: true,
|
||||
ahead: 1,
|
||||
behind: 1,
|
||||
behindCommitsArePatchEquivalent: false
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,39 @@
|
||||
import type { GitUpstreamStatus } from './git-status-types'
|
||||
|
||||
export function upstreamOnlyCommitsArePatchEquivalent(cherryMarkOutput: string): boolean {
|
||||
const lines = cherryMarkOutput
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
return lines.length > 0 && lines.every((line) => line.startsWith('='))
|
||||
let hasCommit = false
|
||||
for (const rawLine of iterateGitOutputLines(cherryMarkOutput)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line) {
|
||||
continue
|
||||
}
|
||||
hasCommit = true
|
||||
if (!line.startsWith('=')) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return hasCommit
|
||||
}
|
||||
|
||||
function* iterateGitOutputLines(output: string): Generator<string> {
|
||||
let lineStart = 0
|
||||
|
||||
for (let index = 0; index < output.length; index++) {
|
||||
const code = output.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield output.slice(lineStart, index)
|
||||
if (code === 13 && output.charCodeAt(index + 1) === 10) {
|
||||
index++
|
||||
}
|
||||
lineStart = index + 1
|
||||
}
|
||||
|
||||
if (lineStart <= output.length) {
|
||||
yield output.slice(lineStart)
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldForcePushWithLeaseForUpstream(
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
GITHUB_PROJECT_REF_INPUT_MAX_BYTES,
|
||||
getGitHubProjectRefInputByteLength,
|
||||
hasBoundedGitHubProjectRefInputText,
|
||||
isGitHubProjectRefInputTooLarge
|
||||
} from './github-project-ref-input'
|
||||
|
||||
describe('GitHub project reference input limits', () => {
|
||||
it('allows normal project references below the byte budget', () => {
|
||||
expect(
|
||||
isGitHubProjectRefInputTooLarge('https://github.com/orgs/acme/projects/42/views/3')
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('measures UTF-8 bytes instead of JavaScript string length', () => {
|
||||
expect(getGitHubProjectRefInputByteLength('\u00e9')).toBe(2)
|
||||
})
|
||||
|
||||
it('rejects oversized pasted project references', () => {
|
||||
expect(isGitHubProjectRefInputTooLarge('x'.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES))).toBe(
|
||||
false
|
||||
)
|
||||
expect(
|
||||
isGitHubProjectRefInputTooLarge('x'.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES + 1))
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects multibyte project references whose character count is below the limit', () => {
|
||||
const reference = '😀'.repeat(Math.floor(GITHUB_PROJECT_REF_INPUT_MAX_BYTES / 4) + 1)
|
||||
|
||||
expect(reference.length).toBeLessThan(GITHUB_PROJECT_REF_INPUT_MAX_BYTES)
|
||||
expect(isGitHubProjectRefInputTooLarge(reference)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects oversized whitespace before submit checks trim the reference', () => {
|
||||
const oversizedWhitespace = ' '.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES + 1)
|
||||
|
||||
expect(isGitHubProjectRefInputTooLarge(oversizedWhitespace)).toBe(true)
|
||||
expect(hasBoundedGitHubProjectRefInputText(oversizedWhitespace)).toBe(false)
|
||||
expect(hasBoundedGitHubProjectRefInputText(' acme/42 ')).toBe(true)
|
||||
expect(hasBoundedGitHubProjectRefInputText(' ')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { getClipboardTextByteLength, isClipboardTextByteLengthOverLimit } from './clipboard-text'
|
||||
|
||||
export const GITHUB_PROJECT_REF_INPUT_MAX_BYTES = 2 * 1024
|
||||
export const GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR = 'Project reference is too large to resolve.'
|
||||
|
||||
export function getGitHubProjectRefInputByteLength(input: string): number {
|
||||
return getClipboardTextByteLength(input)
|
||||
}
|
||||
|
||||
export function isGitHubProjectRefInputTooLarge(
|
||||
input: string,
|
||||
maxBytes = GITHUB_PROJECT_REF_INPUT_MAX_BYTES
|
||||
): boolean {
|
||||
return isClipboardTextByteLengthOverLimit(input, maxBytes)
|
||||
}
|
||||
|
||||
export function hasBoundedGitHubProjectRefInputText(input: string): boolean {
|
||||
return !isGitHubProjectRefInputTooLarge(input) && /\S/.test(input)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
GITHUB_WORK_ITEMS_QUERY_MAX_BYTES,
|
||||
isGitHubWorkItemsQueryTooLarge
|
||||
} from './github-work-items-query-bounds'
|
||||
|
||||
describe('shared GitHub work item query bounds', () => {
|
||||
it('allows normal GitHub search syntax', () => {
|
||||
expect(isGitHubWorkItemsQueryTooLarge('is:issue is:open label:bug')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects oversized pasted work item queries by byte length', () => {
|
||||
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('rejects multibyte pasted queries whose character count is below the limit', () => {
|
||||
const query = '😀'.repeat(Math.floor(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES / 4) + 1)
|
||||
|
||||
expect(query.length).toBeLessThan(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES)
|
||||
expect(isGitHubWorkItemsQueryTooLarge(query)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { isClipboardTextByteLengthOverLimit } from './clipboard-text'
|
||||
|
||||
export const GITHUB_WORK_ITEMS_QUERY_MAX_BYTES = 8 * 1024
|
||||
|
||||
export function isGitHubWorkItemsQueryTooLarge(
|
||||
query: string,
|
||||
maxBytes = GITHUB_WORK_ITEMS_QUERY_MAX_BYTES
|
||||
): boolean {
|
||||
return isClipboardTextByteLengthOverLimit(query, maxBytes)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
hashMarkdownContent,
|
||||
isMarkdownContentByteLengthOverLimit,
|
||||
MOBILE_MARKDOWN_EDIT_MAX_BYTES,
|
||||
utf8ByteLength
|
||||
} from './mobile-markdown-document'
|
||||
|
||||
describe('mobile markdown document byte accounting', () => {
|
||||
it('measures UTF-8 bytes across multibyte code points', () => {
|
||||
expect(utf8ByteLength('aé中😀')).toBe(10)
|
||||
})
|
||||
|
||||
it('keeps markdown content limit checks bounded for oversized multibyte text', () => {
|
||||
const oversized = '😀'.repeat(Math.floor(MOBILE_MARKDOWN_EDIT_MAX_BYTES / 4) + 1)
|
||||
const accepted = '😀'.repeat(Math.floor(MOBILE_MARKDOWN_EDIT_MAX_BYTES / 4))
|
||||
|
||||
expect(isMarkdownContentByteLengthOverLimit(oversized, MOBILE_MARKDOWN_EDIT_MAX_BYTES)).toBe(
|
||||
true
|
||||
)
|
||||
expect(isMarkdownContentByteLengthOverLimit(accepted, MOBILE_MARKDOWN_EDIT_MAX_BYTES)).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('does not depend on TextEncoder for byte length checks', () => {
|
||||
const OriginalTextEncoder = globalThis.TextEncoder
|
||||
vi.stubGlobal(
|
||||
'TextEncoder',
|
||||
class {
|
||||
encode(): Uint8Array {
|
||||
throw new Error('full-buffer encoding should not be used')
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
try {
|
||||
expect(utf8ByteLength('😀')).toBe(4)
|
||||
expect(isMarkdownContentByteLengthOverLimit('😀', 3)).toBe(true)
|
||||
} finally {
|
||||
vi.stubGlobal('TextEncoder', OriginalTextEncoder)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps content hashes prefixed with exact byte length', () => {
|
||||
expect(hashMarkdownContent('😀')).toMatch(/^content:4:/)
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
import { getClipboardTextByteLength, isClipboardTextByteLengthOverLimit } from './clipboard-text'
|
||||
|
||||
export const MOBILE_MARKDOWN_EDIT_MAX_BYTES = 256 * 1024
|
||||
|
||||
export type RuntimeMarkdownReadOnlyReason =
|
||||
@@ -62,6 +64,10 @@ export function hashMarkdownContent(content: string): string {
|
||||
return `content:${utf8ByteLength(content)}:${hash.toString(16).padStart(16, '0')}`
|
||||
}
|
||||
|
||||
export function utf8ByteLength(content: string): number {
|
||||
return new TextEncoder().encode(content).byteLength
|
||||
export function isMarkdownContentByteLengthOverLimit(content: string, maxBytes: number): boolean {
|
||||
return isClipboardTextByteLengthOverLimit(content, maxBytes)
|
||||
}
|
||||
|
||||
export function utf8ByteLength(content: string): number {
|
||||
return getClipboardTextByteLength(content)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
NATIVE_FILE_DROP_MAX_PATH_BYTES,
|
||||
NATIVE_FILE_DROP_MAX_PATHS,
|
||||
NATIVE_FILE_DROP_TARGET,
|
||||
ORCA_INTERNAL_FILE_DRAG_TYPE,
|
||||
createNativeFileDropPayload,
|
||||
createRejectedNativeFileDropPayload,
|
||||
hasNativeFileDragTypes,
|
||||
isNativeFileDropPayload,
|
||||
validateNativeFileDropPaths,
|
||||
resolveNativeFileDropPath
|
||||
} from './native-file-drop'
|
||||
|
||||
@@ -25,15 +31,22 @@ describe('resolveNativeFileDropPath', () => {
|
||||
).toEqual({ target: NATIVE_FILE_DROP_TARGET.projectSidebar })
|
||||
})
|
||||
|
||||
it('preserves terminal tab routing for native file drops', () => {
|
||||
it('preserves terminal tab and pane routing for native file drops', () => {
|
||||
expect(
|
||||
resolveNativeFileDropPath([
|
||||
{
|
||||
terminalPaneLeafId: 'leaf-1'
|
||||
},
|
||||
{
|
||||
nativeFileDropTarget: NATIVE_FILE_DROP_TARGET.terminal,
|
||||
terminalTabId: 'tab-1'
|
||||
}
|
||||
])
|
||||
).toEqual({ target: NATIVE_FILE_DROP_TARGET.terminal, tabId: 'tab-1' })
|
||||
).toEqual({
|
||||
target: NATIVE_FILE_DROP_TARGET.terminal,
|
||||
tabId: 'tab-1',
|
||||
paneLeafId: 'leaf-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the nearest file-explorer destination and fails closed without one', () => {
|
||||
@@ -55,3 +68,210 @@ describe('resolveNativeFileDropPath', () => {
|
||||
).toEqual({ target: 'rejected' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateNativeFileDropPaths', () => {
|
||||
it('rejects native drops by file count before path byte accounting is needed', () => {
|
||||
const paths = Array.from({ length: NATIVE_FILE_DROP_MAX_PATHS + 1 }, (_value, index) =>
|
||||
['/tmp/file-', String(index)].join('')
|
||||
)
|
||||
|
||||
expect(validateNativeFileDropPaths(paths)).toEqual({
|
||||
byteLength: 0,
|
||||
pathCount: NATIVE_FILE_DROP_MAX_PATHS + 1,
|
||||
reason: 'too-many-paths',
|
||||
status: 'rejected'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects native drops whose path list is too large without exposing paths', () => {
|
||||
const validation = validateNativeFileDropPaths(['C:\\Users\\alice\\secret-token.txt'], {
|
||||
maxPathBytes: 4
|
||||
})
|
||||
|
||||
expect(validation).toEqual({
|
||||
byteLength: 5,
|
||||
pathCount: 1,
|
||||
reason: 'paths-too-large',
|
||||
status: 'rejected'
|
||||
})
|
||||
if (validation.status === 'rejected') {
|
||||
const payload = createRejectedNativeFileDropPayload(validation)
|
||||
expect(JSON.stringify(payload)).not.toContain('secret')
|
||||
expect(JSON.stringify(payload)).not.toContain('alice')
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts path payloads within the configured limits', () => {
|
||||
expect(validateNativeFileDropPaths(['/tmp/a', '/tmp/b'])).toEqual({
|
||||
byteLength: 12,
|
||||
pathCount: 2,
|
||||
status: 'accepted'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects multibyte native path lists with bounded byte accounting', () => {
|
||||
expect(validateNativeFileDropPaths(['😀'.repeat(3)], { maxPathBytes: 5 })).toEqual({
|
||||
byteLength: 8,
|
||||
pathCount: 1,
|
||||
reason: 'paths-too-large',
|
||||
status: 'rejected'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createNativeFileDropPayload', () => {
|
||||
it('preserves terminal tab and pane routing in accepted payloads', () => {
|
||||
expect(
|
||||
createNativeFileDropPayload(
|
||||
{ target: NATIVE_FILE_DROP_TARGET.terminal, tabId: 'tab-1', paneLeafId: 'leaf-1' },
|
||||
['/tmp/a']
|
||||
)
|
||||
).toEqual({
|
||||
paneLeafId: 'leaf-1',
|
||||
paths: ['/tmp/a'],
|
||||
tabId: 'tab-1',
|
||||
target: NATIVE_FILE_DROP_TARGET.terminal
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves file explorer destination routing in accepted payloads', () => {
|
||||
expect(
|
||||
createNativeFileDropPayload(
|
||||
{ target: NATIVE_FILE_DROP_TARGET.fileExplorer, destinationDir: '/repo/src' },
|
||||
['/tmp/a']
|
||||
)
|
||||
).toEqual({
|
||||
destinationDir: '/repo/src',
|
||||
paths: ['/tmp/a'],
|
||||
target: NATIVE_FILE_DROP_TARGET.fileExplorer
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to editor for unmarked drops and fails closed for rejected targets', () => {
|
||||
expect(createNativeFileDropPayload(null, ['/tmp/a'])).toEqual({
|
||||
paths: ['/tmp/a'],
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
expect(createNativeFileDropPayload({ target: 'rejected' }, ['/tmp/a'])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns metadata-only rejected payloads for oversized path lists', () => {
|
||||
const payload = createNativeFileDropPayload(null, [
|
||||
'C:\\Users\\alice\\',
|
||||
'a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES)
|
||||
])
|
||||
|
||||
expect(payload).toEqual({
|
||||
byteLength: NATIVE_FILE_DROP_MAX_PATH_BYTES + 1,
|
||||
pathCount: 2,
|
||||
reason: 'paths-too-large',
|
||||
target: 'rejected'
|
||||
})
|
||||
expect(JSON.stringify(payload)).not.toContain('alice')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNativeFileDropPayload', () => {
|
||||
it('accepts bounded native file-drop payload shapes', () => {
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['/tmp/a'],
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
destinationDir: '/repo/src',
|
||||
paths: ['/tmp/a'],
|
||||
target: NATIVE_FILE_DROP_TARGET.fileExplorer
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paneLeafId: 'leaf-1',
|
||||
paths: ['/tmp/a'],
|
||||
tabId: 'tab-1',
|
||||
target: NATIVE_FILE_DROP_TARGET.terminal
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
byteLength: 0,
|
||||
pathCount: NATIVE_FILE_DROP_MAX_PATHS + 1,
|
||||
reason: 'too-many-paths',
|
||||
target: 'rejected'
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects malformed or unbounded native file-drop payloads', () => {
|
||||
expect(isNativeFileDropPayload(null)).toBe(false)
|
||||
expect(isNativeFileDropPayload({ paths: ['/tmp/a'], target: 'browser' })).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['/tmp/a'],
|
||||
target: NATIVE_FILE_DROP_TARGET.fileExplorer
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['/tmp/a'],
|
||||
tabId: 42,
|
||||
target: NATIVE_FILE_DROP_TARGET.terminal
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: Array.from({ length: NATIVE_FILE_DROP_MAX_PATHS + 1 }, () => '/tmp/a'),
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES + 1)],
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
byteLength: 0,
|
||||
pathCount: 1,
|
||||
reason: 'contains-secret-path',
|
||||
target: 'rejected'
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('enforces native file-drop count and byte limits at their boundaries', () => {
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: Array.from(
|
||||
{ length: NATIVE_FILE_DROP_MAX_PATHS },
|
||||
(_value, index) => `/tmp/${index}`
|
||||
),
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: Array.from(
|
||||
{ length: NATIVE_FILE_DROP_MAX_PATHS + 1 },
|
||||
(_value, index) => `/tmp/${index}`
|
||||
),
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES)],
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isNativeFileDropPayload({
|
||||
paths: ['a'.repeat(NATIVE_FILE_DROP_MAX_PATH_BYTES + 1)],
|
||||
target: NATIVE_FILE_DROP_TARGET.editor
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { measureClipboardTextByteLength } from './clipboard-text'
|
||||
|
||||
export const ORCA_INTERNAL_FILE_DRAG_TYPE = 'text/x-orca-file-path'
|
||||
|
||||
export const NATIVE_FILE_DROP_MAX_PATHS = 256
|
||||
export const NATIVE_FILE_DROP_MAX_PATH_BYTES = 256 * 1024
|
||||
|
||||
export const NATIVE_FILE_DROP_TARGET = {
|
||||
editor: 'editor',
|
||||
terminal: 'terminal',
|
||||
@@ -10,7 +15,7 @@ export const NATIVE_FILE_DROP_TARGET = {
|
||||
|
||||
export type NativeDropResolution =
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.editor }
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.terminal; tabId?: string }
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.terminal; tabId?: string; paneLeafId?: string }
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.composer }
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.fileExplorer; destinationDir: string }
|
||||
| { target: typeof NATIVE_FILE_DROP_TARGET.projectSidebar }
|
||||
@@ -18,7 +23,12 @@ export type NativeDropResolution =
|
||||
|
||||
export type NativeFileDropPayload =
|
||||
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.editor }
|
||||
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.terminal; tabId?: string }
|
||||
| {
|
||||
paths: string[]
|
||||
target: typeof NATIVE_FILE_DROP_TARGET.terminal
|
||||
tabId?: string
|
||||
paneLeafId?: string
|
||||
}
|
||||
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.composer }
|
||||
| {
|
||||
paths: string[]
|
||||
@@ -26,11 +36,51 @@ export type NativeFileDropPayload =
|
||||
destinationDir: string
|
||||
}
|
||||
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.projectSidebar }
|
||||
| NativeFileDropRejectedPayload
|
||||
|
||||
export type NativeFileDropRejectedPayload = {
|
||||
byteLength: number
|
||||
pathCount: number
|
||||
reason: 'paths-too-large' | 'too-many-paths'
|
||||
target: 'rejected'
|
||||
}
|
||||
|
||||
export type NativeFileDropPathEntry = {
|
||||
nativeFileDropTarget?: string
|
||||
nativeFileDropDir?: string
|
||||
terminalTabId?: string
|
||||
terminalPaneLeafId?: string
|
||||
}
|
||||
|
||||
export type NativeFileDropPathValidation =
|
||||
| { byteLength: number; pathCount: number; status: 'accepted' }
|
||||
| {
|
||||
byteLength: number
|
||||
pathCount: number
|
||||
reason: NativeFileDropRejectedPayload['reason']
|
||||
status: 'rejected'
|
||||
}
|
||||
|
||||
function isNativeFileDropRejectedReason(
|
||||
reason: unknown
|
||||
): reason is NativeFileDropRejectedPayload['reason'] {
|
||||
return reason === 'paths-too-large' || reason === 'too-many-paths'
|
||||
}
|
||||
|
||||
function isNativeFileDropTarget(target: unknown): target is NativeFileDropPayload['target'] {
|
||||
return Object.values(NATIVE_FILE_DROP_TARGET).includes(target as never) || target === 'rejected'
|
||||
}
|
||||
|
||||
function isOptionalNativeFileDropString(value: unknown): value is string | undefined {
|
||||
return value === undefined || typeof value === 'string'
|
||||
}
|
||||
|
||||
function isNativeFileDropPathList(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((path) => typeof path === 'string')
|
||||
}
|
||||
|
||||
function isNonNegativeFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
||||
}
|
||||
|
||||
function getDataTransferTypes(
|
||||
@@ -51,11 +101,13 @@ export function resolveNativeFileDropPath(
|
||||
): NativeDropResolution | null {
|
||||
let foundExplorer = false
|
||||
let destinationDir: string | undefined
|
||||
let terminalPaneLeafId: string | undefined
|
||||
|
||||
for (const entry of path) {
|
||||
terminalPaneLeafId ??= entry.terminalPaneLeafId
|
||||
const target = entry.nativeFileDropTarget
|
||||
if (target === NATIVE_FILE_DROP_TARGET.terminal) {
|
||||
return { target, tabId: entry.terminalTabId }
|
||||
return { target, tabId: entry.terminalTabId, paneLeafId: terminalPaneLeafId }
|
||||
}
|
||||
if (target === NATIVE_FILE_DROP_TARGET.editor || target === NATIVE_FILE_DROP_TARGET.composer) {
|
||||
return { target }
|
||||
@@ -82,3 +134,136 @@ export function resolveNativeFileDropPath(
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function measureNativeFileDropPathBytes(paths: readonly string[]): number {
|
||||
let byteLength = 0
|
||||
for (const path of paths) {
|
||||
byteLength += measureClipboardTextByteLength(path).byteLength
|
||||
}
|
||||
return byteLength
|
||||
}
|
||||
|
||||
export function validateNativeFileDropPaths(
|
||||
paths: readonly string[],
|
||||
options: {
|
||||
maxPathBytes?: number
|
||||
maxPaths?: number
|
||||
} = {}
|
||||
): NativeFileDropPathValidation {
|
||||
const pathCount = paths.length
|
||||
const maxPaths = options.maxPaths ?? NATIVE_FILE_DROP_MAX_PATHS
|
||||
if (pathCount > maxPaths) {
|
||||
return {
|
||||
byteLength: 0,
|
||||
pathCount,
|
||||
reason: 'too-many-paths',
|
||||
status: 'rejected'
|
||||
}
|
||||
}
|
||||
|
||||
const maxPathBytes = options.maxPathBytes ?? NATIVE_FILE_DROP_MAX_PATH_BYTES
|
||||
let byteLength = 0
|
||||
for (const path of paths) {
|
||||
const measurement = measureClipboardTextByteLength(path, {
|
||||
stopAfterBytes: maxPathBytes - byteLength
|
||||
})
|
||||
byteLength += measurement.byteLength
|
||||
if (byteLength > maxPathBytes) {
|
||||
return {
|
||||
byteLength,
|
||||
pathCount,
|
||||
reason: 'paths-too-large',
|
||||
status: 'rejected'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { byteLength, pathCount, status: 'accepted' }
|
||||
}
|
||||
|
||||
export function createRejectedNativeFileDropPayload(
|
||||
validation: Extract<NativeFileDropPathValidation, { status: 'rejected' }>
|
||||
): NativeFileDropRejectedPayload {
|
||||
return {
|
||||
byteLength: validation.byteLength,
|
||||
pathCount: validation.pathCount,
|
||||
reason: validation.reason,
|
||||
target: 'rejected'
|
||||
}
|
||||
}
|
||||
|
||||
export function createNativeFileDropPayload(
|
||||
resolution: NativeDropResolution | null,
|
||||
paths: readonly string[]
|
||||
): NativeFileDropPayload | null {
|
||||
const validation = validateNativeFileDropPaths(paths)
|
||||
if (validation.status === 'rejected') {
|
||||
return createRejectedNativeFileDropPayload(validation)
|
||||
}
|
||||
|
||||
if (resolution?.target === 'rejected') {
|
||||
return null
|
||||
}
|
||||
|
||||
if (resolution?.target === NATIVE_FILE_DROP_TARGET.fileExplorer) {
|
||||
return {
|
||||
paths: [...paths],
|
||||
target: NATIVE_FILE_DROP_TARGET.fileExplorer,
|
||||
destinationDir: resolution.destinationDir
|
||||
}
|
||||
}
|
||||
|
||||
const target = resolution?.target ?? NATIVE_FILE_DROP_TARGET.editor
|
||||
if (resolution?.target === NATIVE_FILE_DROP_TARGET.terminal) {
|
||||
return {
|
||||
paths: [...paths],
|
||||
target: resolution.target,
|
||||
...(resolution.tabId ? { tabId: resolution.tabId } : {}),
|
||||
...(resolution.paneLeafId ? { paneLeafId: resolution.paneLeafId } : {})
|
||||
}
|
||||
}
|
||||
|
||||
return { paths: [...paths], target }
|
||||
}
|
||||
|
||||
export function isNativeFileDropPayload(value: unknown): value is NativeFileDropPayload {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false
|
||||
}
|
||||
const payload = value as Record<string, unknown>
|
||||
const { target } = payload
|
||||
if (!isNativeFileDropTarget(target)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (target === 'rejected') {
|
||||
return (
|
||||
isNonNegativeFiniteNumber(payload.byteLength) &&
|
||||
isNonNegativeFiniteNumber(payload.pathCount) &&
|
||||
isNativeFileDropRejectedReason(payload.reason)
|
||||
)
|
||||
}
|
||||
|
||||
if (!isNativeFileDropPathList(payload.paths)) {
|
||||
return false
|
||||
}
|
||||
if (validateNativeFileDropPaths(payload.paths).status !== 'accepted') {
|
||||
return false
|
||||
}
|
||||
|
||||
if (target === NATIVE_FILE_DROP_TARGET.terminal) {
|
||||
return (
|
||||
isOptionalNativeFileDropString(payload.tabId) &&
|
||||
isOptionalNativeFileDropString(payload.paneLeafId)
|
||||
)
|
||||
}
|
||||
if (target === NATIVE_FILE_DROP_TARGET.fileExplorer) {
|
||||
return typeof payload.destinationDir === 'string'
|
||||
}
|
||||
|
||||
return (
|
||||
target === NATIVE_FILE_DROP_TARGET.editor ||
|
||||
target === NATIVE_FILE_DROP_TARGET.composer ||
|
||||
target === NATIVE_FILE_DROP_TARGET.projectSidebar
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
const ESC_CODE_UNIT = 0x1b
|
||||
const BEL_CODE_UNIT = 0x07
|
||||
const RIGHT_BRACKET_CODE_UNIT = 0x5d
|
||||
const BACKSLASH_CODE_UNIT = 0x5c
|
||||
const SEMICOLON_CODE_UNIT = 0x3b
|
||||
const OSC_TITLE_COMMANDS = new Set([0x30, 0x31, 0x32])
|
||||
export const MAX_OSC_TITLE_CHARS = 1024
|
||||
|
||||
type OscTitleParseResult =
|
||||
| { kind: 'title'; title: string; nextIndex: number }
|
||||
| { kind: 'invalid'; nextIndex: number }
|
||||
| { kind: 'incomplete' }
|
||||
|
||||
function isOscIntroducerAt(data: string, index: number): boolean {
|
||||
return (
|
||||
data.charCodeAt(index) === ESC_CODE_UNIT &&
|
||||
data.charCodeAt(index + 1) === RIGHT_BRACKET_CODE_UNIT
|
||||
)
|
||||
}
|
||||
|
||||
function parseOscTitleAt(data: string, index: number): OscTitleParseResult {
|
||||
if (!isOscIntroducerAt(data, index)) {
|
||||
return { kind: 'invalid', nextIndex: index + 1 }
|
||||
}
|
||||
if (
|
||||
!OSC_TITLE_COMMANDS.has(data.charCodeAt(index + 2)) ||
|
||||
data.charCodeAt(index + 3) !== SEMICOLON_CODE_UNIT
|
||||
) {
|
||||
return { kind: 'invalid', nextIndex: index + 2 }
|
||||
}
|
||||
|
||||
const titleStart = index + 4
|
||||
for (let cursor = titleStart; cursor < data.length; cursor += 1) {
|
||||
const code = data.charCodeAt(cursor)
|
||||
if (code === BEL_CODE_UNIT) {
|
||||
return {
|
||||
kind: 'title',
|
||||
title: readBoundedOscTitle(data, titleStart, cursor),
|
||||
nextIndex: cursor + 1
|
||||
}
|
||||
}
|
||||
if (code !== ESC_CODE_UNIT) {
|
||||
continue
|
||||
}
|
||||
if (data.charCodeAt(cursor + 1) === BACKSLASH_CODE_UNIT) {
|
||||
return {
|
||||
kind: 'title',
|
||||
title: readBoundedOscTitle(data, titleStart, cursor),
|
||||
nextIndex: cursor + 2
|
||||
}
|
||||
}
|
||||
return { kind: 'invalid', nextIndex: cursor }
|
||||
}
|
||||
|
||||
return { kind: 'incomplete' }
|
||||
}
|
||||
|
||||
function readBoundedOscTitle(data: string, titleStart: number, titleEnd: number): string {
|
||||
// Why: PTY output can contain pasted or remote-controlled OSC titles; keep
|
||||
// downstream title detection bounded while preserving trailing status words.
|
||||
const length = titleEnd - titleStart
|
||||
if (length <= MAX_OSC_TITLE_CHARS) {
|
||||
return data.slice(titleStart, titleEnd)
|
||||
}
|
||||
const prefixLength = Math.ceil(MAX_OSC_TITLE_CHARS / 2)
|
||||
const suffixLength = MAX_OSC_TITLE_CHARS - prefixLength
|
||||
return (
|
||||
data.slice(titleStart, titleStart + prefixLength) +
|
||||
data.slice(titleEnd - suffixLength, titleEnd)
|
||||
)
|
||||
}
|
||||
|
||||
export function extractLastOscTitle(data: string): string | null {
|
||||
if (!data.includes('\x1b]')) {
|
||||
return null
|
||||
}
|
||||
|
||||
let last: string | null = null
|
||||
let searchStart = 0
|
||||
// Why: raw PTY chunks can include large pasted content. Parse OSC titles
|
||||
// directly instead of running a global regex over the whole chunk.
|
||||
while (searchStart < data.length) {
|
||||
const start = data.indexOf('\x1b]', searchStart)
|
||||
if (start === -1) {
|
||||
break
|
||||
}
|
||||
const parsed = parseOscTitleAt(data, start)
|
||||
if (parsed.kind === 'incomplete') {
|
||||
break
|
||||
}
|
||||
if (parsed.kind === 'title') {
|
||||
last = parsed.title
|
||||
searchStart = parsed.nextIndex
|
||||
continue
|
||||
}
|
||||
searchStart = parsed.nextIndex
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
export function extractAllOscTitles(data: string): string[] {
|
||||
if (!data.includes('\x1b]')) {
|
||||
return []
|
||||
}
|
||||
|
||||
const titles: string[] = []
|
||||
let searchStart = 0
|
||||
while (searchStart < data.length) {
|
||||
const start = data.indexOf('\x1b]', searchStart)
|
||||
if (start === -1) {
|
||||
break
|
||||
}
|
||||
const parsed = parseOscTitleAt(data, start)
|
||||
if (parsed.kind === 'incomplete') {
|
||||
break
|
||||
}
|
||||
if (parsed.kind === 'title') {
|
||||
titles.push(parsed.title)
|
||||
searchStart = parsed.nextIndex
|
||||
continue
|
||||
}
|
||||
searchStart = parsed.nextIndex
|
||||
}
|
||||
return titles
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
export type PastePayloadCorpusCase = {
|
||||
hasRichText?: boolean
|
||||
name: string
|
||||
text: string
|
||||
expected: {
|
||||
hasControlSequences: boolean
|
||||
lineCount: number
|
||||
}
|
||||
}
|
||||
|
||||
const GRAVE_ACCENT = String.fromCharCode(0x60)
|
||||
|
||||
// Why: paste safety tests should exercise the same risky payload shapes
|
||||
// without snapshotting or logging clipboard-like content.
|
||||
export const PASTE_PAYLOAD_CORPUS: PastePayloadCorpusCase[] = [
|
||||
{
|
||||
name: 'simple text',
|
||||
text: 'simple text',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'single line with spaces',
|
||||
text: 'single line with several spaces',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'multiline LF',
|
||||
text: 'alpha\nbeta\ngamma',
|
||||
expected: { hasControlSequences: false, lineCount: 3 }
|
||||
},
|
||||
{
|
||||
name: 'multiline CRLF',
|
||||
text: 'alpha\r\nbeta\r\ngamma',
|
||||
expected: { hasControlSequences: false, lineCount: 3 }
|
||||
},
|
||||
{
|
||||
name: 'mixed newline text',
|
||||
text: 'alpha\r\nbeta\ngamma\rdelta',
|
||||
expected: { hasControlSequences: false, lineCount: 4 }
|
||||
},
|
||||
{
|
||||
name: 'PowerShell metacharacters',
|
||||
text: ['PowerShell: ', GRAVE_ACCENT, ' $ " \' ; | & < > @ { } ( )'].join(''),
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'cmd metacharacters',
|
||||
text: 'cmd: %PATH% !VAR! ^ & | < >',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'POSIX shell metacharacters',
|
||||
text: ['POSIX: $ ', GRAVE_ACCENT, ' " \' ; | & < > * ? [ ] ( )'].join(''),
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'Windows path with spaces',
|
||||
text: 'C:\\Users\\Name\\My Project\\file.txt',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'UNC path',
|
||||
text: '\\\\server\\share\\folder\\file.txt',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'WSL UNC path',
|
||||
text: '\\\\wsl$\\Ubuntu-24.04\\home\\user\\repo',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'POSIX path with spaces',
|
||||
text: '/home/user/my project/file.txt',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'Unicode',
|
||||
text: 'café 你好 مرحبا 😀',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'RTL and combining marks',
|
||||
text: 'עברית e\u0301 عربى',
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'long single line',
|
||||
text: 'x'.repeat(1024),
|
||||
expected: { hasControlSequences: false, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'large multiline text',
|
||||
text: Array.from({ length: 32 }, (_value, index) => ['line-', String(index)].join('')).join(
|
||||
'\n'
|
||||
),
|
||||
expected: { hasControlSequences: false, lineCount: 32 }
|
||||
},
|
||||
{
|
||||
name: 'ANSI control sequence',
|
||||
text: 'before\x1b[31mafter',
|
||||
expected: { hasControlSequences: true, lineCount: 1 }
|
||||
},
|
||||
{
|
||||
name: 'browser rich-text plain fallback',
|
||||
text: 'Heading\nplain text fallback',
|
||||
hasRichText: true,
|
||||
expected: { hasControlSequences: false, lineCount: 2 }
|
||||
}
|
||||
]
|
||||
@@ -21,6 +21,7 @@ describe('detectPiAgentKindFromCommand', () => {
|
||||
it('returns "omp" for omp launched via an absolute path', () => {
|
||||
expect(detectPiAgentKindFromCommand('/usr/local/bin/omp')).toBe('omp')
|
||||
expect(detectPiAgentKindFromCommand('~/bin/omp.sh')).toBe('omp')
|
||||
expect(detectPiAgentKindFromCommand('"C:\\Program Files\\Orca\\omp.exe" --resume')).toBe('omp')
|
||||
})
|
||||
|
||||
it('returns "pi" for pi launched via an absolute path', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { TUI_AGENT_CONFIG } from './tui-agent-config'
|
||||
import { getCommandTokenPathBasename, getFirstCommandToken } from './command-token-scanner'
|
||||
|
||||
/**
|
||||
* Pi-compatible agent kinds. Both Pi and OMP (omp.sh) consume the same
|
||||
@@ -27,7 +28,7 @@ const PATH_PREFIX = `(?:[^\\s;&|('"\`]*[\\\\/])?`
|
||||
function makeLaunchCmdRegex(launchCmd: string): RegExp {
|
||||
// Why: launchCmd may be a multi-token string ("hermes --tui"); only the
|
||||
// first token is the binary name. Use that for matching.
|
||||
const binary = launchCmd.split(/\s+/, 1)[0]
|
||||
const binary = getCommandTokenPathBasename(getFirstCommandToken(launchCmd))
|
||||
const escaped = binary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
return new RegExp(
|
||||
`${BOUNDARY_BEFORE}${PATH_PREFIX}${escaped}(?:\\.cmd|\\.exe|\\.sh)?${BOUNDARY_AFTER}`,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
getProcessOutputFields,
|
||||
iterateProcessOutputLines,
|
||||
PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS
|
||||
} from './process-output-field-scanner'
|
||||
|
||||
describe('iterateProcessOutputLines', () => {
|
||||
it('walks LF, CRLF, and CR lines without returning a trailing synthetic line', () => {
|
||||
expect([...iterateProcessOutputLines('alpha\nbeta\r\ngamma\rdelta\n')]).toEqual([
|
||||
'alpha',
|
||||
'beta',
|
||||
'gamma',
|
||||
'delta'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getProcessOutputFields', () => {
|
||||
it('returns bounded whitespace-separated fields', () => {
|
||||
expect(
|
||||
getProcessOutputFields(' TCP\t127.0.0.1:3000 0.0.0.0:0 LISTENING 4242 extra', 5)
|
||||
).toEqual(['TCP', '127.0.0.1:3000', '0.0.0.0:0', 'LISTENING', '4242'])
|
||||
})
|
||||
|
||||
it('does not use regex whitespace splitting', () => {
|
||||
const splitSpy = vi.spyOn(String.prototype, 'split')
|
||||
|
||||
getProcessOutputFields('alpha beta gamma', 2)
|
||||
|
||||
const usedWhitespaceFieldSplit = splitSpy.mock.calls.some(
|
||||
([separator]) => separator instanceof RegExp && separator.source.includes('\\s+')
|
||||
)
|
||||
splitSpy.mockRestore()
|
||||
expect(usedWhitespaceFieldSplit).toBe(false)
|
||||
})
|
||||
|
||||
it('caps scan work for oversized rows', () => {
|
||||
const fields = getProcessOutputFields('x'.repeat(PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS + 100), 2)
|
||||
|
||||
expect(fields).toEqual(['x'.repeat(PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS)])
|
||||
})
|
||||
|
||||
it('keeps a field that ends exactly at the scan boundary', () => {
|
||||
const boundaryField = 'x'.repeat(PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS)
|
||||
|
||||
expect(getProcessOutputFields(boundaryField, 1)).toEqual([boundaryField])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
export const PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS = 4096
|
||||
|
||||
// Why: process output can be multi-MB; callers should not materialize every line up front.
|
||||
export function* iterateProcessOutputLines(output: string): Generator<string> {
|
||||
let lineStart = 0
|
||||
|
||||
for (let index = 0; index < output.length; index += 1) {
|
||||
const code = output.charCodeAt(index)
|
||||
if (code !== 10 && code !== 13) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield output.slice(lineStart, index)
|
||||
if (code === 13 && output.charCodeAt(index + 1) === 10) {
|
||||
index += 1
|
||||
}
|
||||
lineStart = index + 1
|
||||
}
|
||||
|
||||
if (lineStart < output.length) {
|
||||
yield output.slice(lineStart)
|
||||
}
|
||||
}
|
||||
|
||||
// Why: command output can include noisy paste-sized rows; port scanners only need early fields.
|
||||
export function getProcessOutputFields(line: string, maxFields: number): string[] {
|
||||
if (maxFields <= 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const fields: string[] = []
|
||||
const scanLimit = Math.min(line.length, PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS)
|
||||
let tokenStart = -1
|
||||
|
||||
for (let index = 0; index <= scanLimit; index += 1) {
|
||||
const isEnd = index === scanLimit
|
||||
if (!isEnd && !isProcessOutputWhitespace(line.charCodeAt(index))) {
|
||||
if (tokenStart === -1) {
|
||||
tokenStart = index
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (tokenStart === -1) {
|
||||
continue
|
||||
}
|
||||
|
||||
fields.push(line.slice(tokenStart, index))
|
||||
tokenStart = -1
|
||||
if (fields.length >= maxFields) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
function isProcessOutputWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildPullRequestFieldsPrompt,
|
||||
parseGeneratedPullRequestFields,
|
||||
@@ -17,6 +17,10 @@ const context: PullRequestDraftContext = {
|
||||
patch: 'diff --git a/src/file.ts b/src/file.ts\n+export const value = true'
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('buildPullRequestFieldsPrompt', () => {
|
||||
it('asks for compact JSON and includes PR context', () => {
|
||||
const prompt = buildPullRequestFieldsPrompt(context, 'Use conventional PR titles.')
|
||||
@@ -57,6 +61,28 @@ describe('parseGeneratedPullRequestFields', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('parses CRLF fenced JSON output without full-string fence matching', () => {
|
||||
const matchSpy = vi.spyOn(String.prototype, 'match')
|
||||
const replaceSpy = vi.spyOn(String.prototype, 'replace')
|
||||
const fields = parseGeneratedPullRequestFields(
|
||||
'```JSON\r\n{"base":"main","title":"fix: add details.","body":"Summary","draft":true}\r\n```',
|
||||
context
|
||||
)
|
||||
|
||||
expect(fields.title).toBe('fix: add details')
|
||||
const usedFenceMatch = matchSpy.mock.calls.some(
|
||||
([pattern]) =>
|
||||
pattern instanceof RegExp &&
|
||||
pattern.source.startsWith('^```') &&
|
||||
pattern.source.includes('[\\s\\S]')
|
||||
)
|
||||
const usedCrlfReplace = replaceSpy.mock.calls.some(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\r\\n' && pattern.global
|
||||
)
|
||||
expect(usedFenceMatch).toBe(false)
|
||||
expect(usedCrlfReplace).toBe(false)
|
||||
})
|
||||
|
||||
it('falls back for missing optional values', () => {
|
||||
const fields = parseGeneratedPullRequestFields('{"title":""}', context)
|
||||
|
||||
|
||||
@@ -85,10 +85,10 @@ export function buildPullRequestFieldsPrompt(
|
||||
}
|
||||
|
||||
function stripJsonFence(raw: string): string {
|
||||
let text = raw.replace(/\r\n/g, '\n').trim()
|
||||
const fenced = text.match(/^```(?:json)?\n([\s\S]*?)\n```$/i)
|
||||
if (fenced) {
|
||||
text = fenced[1].trim()
|
||||
let text = raw.trim()
|
||||
const fencedBody = getJsonFenceBody(text)
|
||||
if (fencedBody !== null) {
|
||||
text = fencedBody.trim()
|
||||
}
|
||||
const start = text.indexOf('{')
|
||||
const end = text.lastIndexOf('}')
|
||||
@@ -98,6 +98,56 @@ function stripJsonFence(raw: string): string {
|
||||
return text
|
||||
}
|
||||
|
||||
function getJsonFenceBody(text: string): string | null {
|
||||
let bodyStart = getLineBreakEnd(text, 3)
|
||||
if (bodyStart === null && startsWithAsciiIgnoreCase(text, '```json', 0)) {
|
||||
bodyStart = getLineBreakEnd(text, 7)
|
||||
}
|
||||
if (bodyStart === null || !text.endsWith('```')) {
|
||||
return null
|
||||
}
|
||||
|
||||
const closeStart = text.length - 3
|
||||
const bodyEnd = getBodyEndBeforeClosingFence(text, closeStart)
|
||||
return bodyEnd === null ? null : text.slice(bodyStart, bodyEnd)
|
||||
}
|
||||
|
||||
function getLineBreakEnd(text: string, index: number): number | null {
|
||||
const code = text.charCodeAt(index)
|
||||
if (code === 10) {
|
||||
return index + 1
|
||||
}
|
||||
if (code === 13) {
|
||||
return text.charCodeAt(index + 1) === 10 ? index + 2 : index + 1
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function getBodyEndBeforeClosingFence(text: string, closeStart: number): number | null {
|
||||
const previousCode = text.charCodeAt(closeStart - 1)
|
||||
if (previousCode === 10) {
|
||||
return text.charCodeAt(closeStart - 2) === 13 ? closeStart - 2 : closeStart - 1
|
||||
}
|
||||
if (previousCode === 13) {
|
||||
return closeStart - 1
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function startsWithAsciiIgnoreCase(value: string, search: string, startIndex: number): boolean {
|
||||
if (startIndex < 0 || startIndex + search.length > value.length) {
|
||||
return false
|
||||
}
|
||||
for (let index = 0; index < search.length; index++) {
|
||||
const code = value.charCodeAt(startIndex + index)
|
||||
const normalizedCode = code >= 65 && code <= 90 ? code + 32 : code
|
||||
if (normalizedCode !== search.charCodeAt(index)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export function parseGeneratedPullRequestFields(
|
||||
raw: string,
|
||||
fallback: Pick<PullRequestDraftContext, 'base' | 'currentTitle' | 'currentBody' | 'currentDraft'>
|
||||
|
||||
@@ -60,12 +60,16 @@ export type SshConnectionStatus =
|
||||
| 'reconnection-failed'
|
||||
| 'error'
|
||||
|
||||
export type SshRemotePlatform = 'linux' | 'darwin' | 'win32'
|
||||
|
||||
export type SshConnectionState = {
|
||||
targetId: string
|
||||
status: SshConnectionStatus
|
||||
error: string | null
|
||||
/** Number of reconnection attempts since last disconnect. */
|
||||
reconnectAttempt: number
|
||||
/** Remote OS detected by the SSH relay once available. */
|
||||
remotePlatform?: SshRemotePlatform
|
||||
}
|
||||
|
||||
export type SshRemotePtyLeaseState = 'attached' | 'detached' | 'terminated' | 'expired'
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
TERMINAL_INPUT_CHUNK_MAX_BYTES,
|
||||
TERMINAL_INPUT_TOO_LARGE_ERROR,
|
||||
assertTerminalInputWithinLimit,
|
||||
getTerminalInputByteLength,
|
||||
iterateTerminalInputChunks,
|
||||
isTerminalInputTooLarge,
|
||||
isTerminalInputTooLargeWithDeferredMeasurement,
|
||||
isTerminalInputTooLargeWithYield,
|
||||
splitTerminalInputChunks
|
||||
} from './terminal-input'
|
||||
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from './clipboard-text'
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('terminal input bounds', () => {
|
||||
it('keeps small terminal input as one chunk', () => {
|
||||
expect(splitTerminalInputChunks('npm test')).toEqual(['npm test'])
|
||||
})
|
||||
|
||||
it('splits by UTF-8 bytes without splitting surrogate pairs', () => {
|
||||
const chunks = splitTerminalInputChunks('ab😀cd', 4)
|
||||
|
||||
expect(chunks).toEqual(['ab', '😀', 'cd'])
|
||||
expect(chunks.join('')).toBe('ab😀cd')
|
||||
})
|
||||
|
||||
it('uses 16KB as the default terminal input chunk budget', () => {
|
||||
const chunks = splitTerminalInputChunks('x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES + 1))
|
||||
|
||||
expect(chunks).toEqual(['x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES), 'x'])
|
||||
})
|
||||
|
||||
it('iterates chunks lazily without prebuilding every terminal input chunk', () => {
|
||||
const chunks = iterateTerminalInputChunks('abcdefghij', 4)
|
||||
|
||||
expect(chunks.next()).toEqual({ done: false, value: 'abcd' })
|
||||
expect(chunks.next()).toEqual({ done: false, value: 'efgh' })
|
||||
expect(chunks.next()).toEqual({ done: false, value: 'ij' })
|
||||
expect(chunks.next()).toEqual({ done: true, value: undefined })
|
||||
})
|
||||
|
||||
it('does not scan the full payload before yielding the first chunk', () => {
|
||||
const codePointAt = vi.spyOn(String.prototype, 'codePointAt')
|
||||
const text = 'x'.repeat(128)
|
||||
const chunks = iterateTerminalInputChunks(text, 8)
|
||||
|
||||
expect(chunks.next()).toEqual({ done: false, value: 'x'.repeat(8) })
|
||||
|
||||
expect(codePointAt.mock.calls.length).toBeLessThan(text.length)
|
||||
})
|
||||
|
||||
it('measures UTF-8 bytes for terminal input without using UTF-16 length', () => {
|
||||
expect(getTerminalInputByteLength('a😀')).toBe(5)
|
||||
})
|
||||
|
||||
it('keeps a single multibyte terminal character intact when the byte cap is smaller', () => {
|
||||
const chunks = splitTerminalInputChunks('😀a', 1)
|
||||
|
||||
expect(chunks).toEqual(['😀', 'a'])
|
||||
expect(chunks.join('')).toBe('😀a')
|
||||
})
|
||||
|
||||
it('rejects oversized terminal input with a metadata-only error', () => {
|
||||
const secret = 'terminal-secret-token'
|
||||
const payload = [secret, 'payload'].join('')
|
||||
|
||||
expect(() => assertTerminalInputWithinLimit(payload, 4)).toThrow(TERMINAL_INPUT_TOO_LARGE_ERROR)
|
||||
expect(() => assertTerminalInputWithinLimit(payload, 4)).not.toThrow(secret)
|
||||
})
|
||||
|
||||
it('rejects multibyte oversized terminal input at the byte boundary', () => {
|
||||
expect(isTerminalInputTooLarge('😀'.repeat(3), 5)).toBe(true)
|
||||
expect(() => assertTerminalInputWithinLimit('😀'.repeat(3), 5)).toThrow(
|
||||
TERMINAL_INPUT_TOO_LARGE_ERROR
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects terminal input whose string length already exceeds the byte limit without scanning', () => {
|
||||
const codePointAt = vi.spyOn(String.prototype, 'codePointAt')
|
||||
|
||||
expect(isTerminalInputTooLarge('x'.repeat(6), 5)).toBe(true)
|
||||
expect(() => assertTerminalInputWithinLimit('x'.repeat(6), 5)).toThrow(
|
||||
TERMINAL_INPUT_TOO_LARGE_ERROR
|
||||
)
|
||||
expect(codePointAt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('yields while measuring accepted large terminal input', async () => {
|
||||
vi.useFakeTimers()
|
||||
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
|
||||
const result = isTerminalInputTooLargeWithYield(text, text.length * 3)
|
||||
let settled = false
|
||||
void result.then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
|
||||
expect(settled).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
await expect(result).resolves.toBe(false)
|
||||
})
|
||||
|
||||
it('keeps deferred terminal input validation synchronous for small or obvious oversized input', () => {
|
||||
expect(isTerminalInputTooLargeWithDeferredMeasurement('npm test')).toBe(false)
|
||||
expect(isTerminalInputTooLargeWithDeferredMeasurement('x'.repeat(6), 5)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns a pending validation for accepted large terminal input', async () => {
|
||||
vi.useFakeTimers()
|
||||
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
|
||||
const result = isTerminalInputTooLargeWithDeferredMeasurement(text, text.length * 3)
|
||||
let settled = false
|
||||
void Promise.resolve(result).then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
|
||||
expect(result).toBeInstanceOf(Promise)
|
||||
expect(settled).toBe(false)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
await expect(result).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import {
|
||||
CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS,
|
||||
isClipboardTextByteLengthOverLimitWithYield,
|
||||
measureClipboardTextByteLength
|
||||
} from './clipboard-text'
|
||||
|
||||
export const TERMINAL_INPUT_CHUNK_MAX_BYTES = 16 * 1024
|
||||
export const TERMINAL_INPUT_MAX_BYTES = 16 * 1024 * 1024
|
||||
export const TERMINAL_INPUT_TOO_LARGE_ERROR =
|
||||
'Terminal input is too large for a safe terminal send.'
|
||||
|
||||
export function getTerminalInputByteLength(text: string): number {
|
||||
return measureClipboardTextByteLength(text).byteLength
|
||||
}
|
||||
|
||||
function getUtf8ByteLengthForCodePoint(codePoint: number): number {
|
||||
if (codePoint <= 0x7f) {
|
||||
return 1
|
||||
}
|
||||
if (codePoint <= 0x7ff) {
|
||||
return 2
|
||||
}
|
||||
if (codePoint <= 0xffff) {
|
||||
return 3
|
||||
}
|
||||
return 4
|
||||
}
|
||||
|
||||
export function assertTerminalInputWithinLimit(
|
||||
text: string,
|
||||
maxBytes = TERMINAL_INPUT_MAX_BYTES
|
||||
): string {
|
||||
if (isTerminalInputTooLarge(text, maxBytes)) {
|
||||
throw new Error(TERMINAL_INPUT_TOO_LARGE_ERROR)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export function isTerminalInputTooLarge(
|
||||
text: string,
|
||||
maxBytes = TERMINAL_INPUT_MAX_BYTES
|
||||
): boolean {
|
||||
return (
|
||||
text.length > maxBytes ||
|
||||
measureClipboardTextByteLength(text, { stopAfterBytes: maxBytes }).exceededLimit
|
||||
)
|
||||
}
|
||||
|
||||
export function isTerminalInputTooLargeWithYield(
|
||||
text: string,
|
||||
maxBytes = TERMINAL_INPUT_MAX_BYTES
|
||||
): Promise<boolean> {
|
||||
return isClipboardTextByteLengthOverLimitWithYield(text, maxBytes)
|
||||
}
|
||||
|
||||
export function isTerminalInputTooLargeWithDeferredMeasurement(
|
||||
text: string,
|
||||
maxBytes = TERMINAL_INPUT_MAX_BYTES
|
||||
): boolean | Promise<boolean> {
|
||||
if (text.length > maxBytes) {
|
||||
return true
|
||||
}
|
||||
if (text.length > CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS) {
|
||||
return isTerminalInputTooLargeWithYield(text, maxBytes)
|
||||
}
|
||||
return isTerminalInputTooLarge(text, maxBytes)
|
||||
}
|
||||
|
||||
export function splitTerminalInputChunks(
|
||||
text: string,
|
||||
maxChunkBytes = TERMINAL_INPUT_CHUNK_MAX_BYTES
|
||||
): string[] {
|
||||
return [...iterateTerminalInputChunks(text, maxChunkBytes)]
|
||||
}
|
||||
|
||||
export function* iterateTerminalInputChunks(
|
||||
text: string,
|
||||
maxChunkBytes = TERMINAL_INPUT_CHUNK_MAX_BYTES
|
||||
): Generator<string> {
|
||||
if (text.length === 0) {
|
||||
return
|
||||
}
|
||||
const normalizedMax = Number.isFinite(maxChunkBytes) && maxChunkBytes > 0 ? maxChunkBytes : 1
|
||||
const measurement = measureClipboardTextByteLength(text, { stopAfterBytes: normalizedMax })
|
||||
if (!measurement.exceededLimit) {
|
||||
yield text
|
||||
return
|
||||
}
|
||||
|
||||
let currentStart = 0
|
||||
let currentBytes = 0
|
||||
let index = 0
|
||||
while (index < text.length) {
|
||||
const codePoint = text.codePointAt(index) ?? 0
|
||||
const codeUnitLength = codePoint > 0xffff ? 2 : 1
|
||||
const nextIndex = index + codeUnitLength
|
||||
const characterBytes = getUtf8ByteLengthForCodePoint(codePoint)
|
||||
if (currentBytes > 0 && currentBytes + characterBytes > normalizedMax) {
|
||||
yield text.slice(currentStart, index)
|
||||
currentStart = index
|
||||
currentBytes = 0
|
||||
}
|
||||
currentBytes += characterBytes
|
||||
index = nextIndex
|
||||
}
|
||||
if (currentStart < text.length) {
|
||||
yield text.slice(currentStart)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
export function foldWorkspaceNameWhitespaceToHyphen(input: string): string {
|
||||
let result = ''
|
||||
let pendingHyphen = false
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
if (isWorkspaceNameWhitespace(input.charCodeAt(index))) {
|
||||
pendingHyphen = true
|
||||
continue
|
||||
}
|
||||
if (pendingHyphen) {
|
||||
result += '-'
|
||||
pendingHyphen = false
|
||||
}
|
||||
result += input[index]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function collectCompactWorkspaceWords(
|
||||
input: string,
|
||||
maxWords: number,
|
||||
stopWords: ReadonlySet<string>
|
||||
): string[] {
|
||||
const words: string[] = []
|
||||
let tokenStart = -1
|
||||
for (let index = 0; index <= input.length; index += 1) {
|
||||
const isEnd = index === input.length
|
||||
if (!isEnd && startsWithHttpUrl(input, index)) {
|
||||
index = finishCompactWorkspaceToken(input, tokenStart, index, words, maxWords, stopWords)
|
||||
tokenStart = -1
|
||||
while (index < input.length && !isWorkspaceNameWhitespace(input.charCodeAt(index))) {
|
||||
index += 1
|
||||
}
|
||||
if (words.length >= maxWords) {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!isEnd && !isCompactWorkspaceWordSeparator(input.charCodeAt(index))) {
|
||||
if (tokenStart === -1) {
|
||||
tokenStart = index
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (tokenStart !== -1) {
|
||||
finishCompactWorkspaceToken(input, tokenStart, index, words, maxWords, stopWords)
|
||||
tokenStart = -1
|
||||
if (words.length >= maxWords) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return words
|
||||
}
|
||||
|
||||
function finishCompactWorkspaceToken(
|
||||
input: string,
|
||||
tokenStart: number,
|
||||
tokenEnd: number,
|
||||
words: string[],
|
||||
maxWords: number,
|
||||
stopWords: ReadonlySet<string>
|
||||
): number {
|
||||
if (tokenStart === -1 || words.length >= maxWords) {
|
||||
return tokenEnd
|
||||
}
|
||||
const word = input.slice(tokenStart, tokenEnd)
|
||||
if (word && !stopWords.has(word.toLowerCase())) {
|
||||
words.push(word)
|
||||
}
|
||||
return tokenEnd
|
||||
}
|
||||
|
||||
function startsWithHttpUrl(input: string, index: number): boolean {
|
||||
return (
|
||||
startsWithAsciiInsensitive(input, index, 'http://') ||
|
||||
startsWithAsciiInsensitive(input, index, 'https://')
|
||||
)
|
||||
}
|
||||
|
||||
function startsWithAsciiInsensitive(input: string, index: number, prefix: string): boolean {
|
||||
if (index + prefix.length > input.length) {
|
||||
return false
|
||||
}
|
||||
for (let offset = 0; offset < prefix.length; offset += 1) {
|
||||
if (toLowerAsciiCode(input.charCodeAt(index + offset)) !== prefix.charCodeAt(offset)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function toLowerAsciiCode(code: number): number {
|
||||
return code >= 65 && code <= 90 ? code + 32 : code
|
||||
}
|
||||
|
||||
function isCompactWorkspaceWordSeparator(code: number): boolean {
|
||||
return (
|
||||
isWorkspaceNameWhitespace(code) ||
|
||||
code === 34 ||
|
||||
code === 35 ||
|
||||
code === 40 ||
|
||||
code === 41 ||
|
||||
code === 47 ||
|
||||
code === 58 ||
|
||||
code === 91 ||
|
||||
code === 92 ||
|
||||
code === 93 ||
|
||||
code === 95 ||
|
||||
code === 123 ||
|
||||
code === 125 ||
|
||||
code === 45
|
||||
)
|
||||
}
|
||||
|
||||
function isWorkspaceNameWhitespace(code: number): boolean {
|
||||
return (
|
||||
code === 32 ||
|
||||
(code >= 9 && code <= 13) ||
|
||||
code === 160 ||
|
||||
code === 5760 ||
|
||||
(code >= 8192 && code <= 8202) ||
|
||||
code === 8232 ||
|
||||
code === 8233 ||
|
||||
code === 8239 ||
|
||||
code === 8287 ||
|
||||
code === 12288 ||
|
||||
code === 65279
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
getLinearIssueWorkspaceName,
|
||||
getLinkedWorkItemSuggestedName,
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
slugifyForWorkspaceName
|
||||
} from './workspace-name'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('slugifyForWorkspaceName', () => {
|
||||
it('keeps workspace seed slugs short, ascii-safe, and git-ref-safe', () => {
|
||||
expect(slugifyForWorkspaceName('../../Fix mobile Tasks 🚀')).toBe('fix-mobile-tasks')
|
||||
@@ -23,6 +27,18 @@ describe('slugifyForWorkspaceName', () => {
|
||||
'cant-enable-browser-notifications'
|
||||
)
|
||||
})
|
||||
|
||||
it('folds pasted workspace-name whitespace without regex replacement', () => {
|
||||
const replace = vi.spyOn(String.prototype, 'replace')
|
||||
const name = ['Fix', String.fromCharCode(160), '\nPasted\tWorkspace'].join('')
|
||||
|
||||
expect(slugifyForWorkspaceName(name)).toBe('fix-pasted-workspace')
|
||||
expect(
|
||||
replace.mock.calls.filter(
|
||||
([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+'
|
||||
)
|
||||
).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getLinkedWorkItemSuggestedName', () => {
|
||||
@@ -215,6 +231,24 @@ describe('getWorkspaceIntentName', () => {
|
||||
seedName: 'add-keyboard-shortcut-settings'
|
||||
})
|
||||
})
|
||||
|
||||
it('compacts pasted task text without whitespace regex splitting', () => {
|
||||
const split = vi.spyOn(String.prototype, 'split')
|
||||
const sourceText = [
|
||||
'https://github.com/acme/app/issues/123',
|
||||
'\nadd',
|
||||
String.fromCharCode(160),
|
||||
'keyboard\tshortcut settings'
|
||||
].join('')
|
||||
|
||||
expect(getWorkspaceIntentName({ sourceText })).toEqual({
|
||||
displayName: 'Add Keyboard Shortcut Settings',
|
||||
seedName: 'add-keyboard-shortcut-settings'
|
||||
})
|
||||
expect(
|
||||
split.mock.calls.filter(([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+')
|
||||
).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getLinearIssueWorkspaceName', () => {
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
collectCompactWorkspaceWords,
|
||||
foldWorkspaceNameWhitespaceToHyphen
|
||||
} from './workspace-name-text-scanner'
|
||||
|
||||
function normalizeApostrophes(input: string): string {
|
||||
return input.replace(/[‘’]/g, "'")
|
||||
}
|
||||
@@ -15,12 +20,12 @@ function stripDanglingDisplayApostrophes(input: string): string {
|
||||
}
|
||||
|
||||
export function slugifyForWorkspaceName(input: string): string {
|
||||
const normalized = removeIntraWordApostrophes(input)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\\/]+/g, '-')
|
||||
return (
|
||||
removeIntraWordApostrophes(input)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\\/]+/g, '-')
|
||||
.replace(/\s+/g, '-')
|
||||
foldWorkspaceNameWhitespaceToHyphen(normalized)
|
||||
.replace(/[^a-z0-9._-]+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
// Why: git check-ref-format rejects any ref containing `..`, so previews
|
||||
@@ -120,17 +125,14 @@ function titleCaseWord(word: string): string {
|
||||
}
|
||||
|
||||
function compactWords(input: string, maxWords = 4): string {
|
||||
return stripDanglingDisplayApostrophes(input)
|
||||
.replace(/https?:\/\/\S+/gi, ' ')
|
||||
.replace(/[()[\]{}"]/g, ' ')
|
||||
.replace(/[#/\\:_-]+/g, ' ')
|
||||
.split(/\s+/)
|
||||
.map((word) => word.trim())
|
||||
.filter(Boolean)
|
||||
.filter((word) => !STOP_WORDS.has(word.toLowerCase()))
|
||||
.slice(0, maxWords)
|
||||
.map(titleCaseWord)
|
||||
.join(' ')
|
||||
// Why: workspace names can be derived from pasted prompts/URLs; collect only
|
||||
// the visible words we need instead of splitting the full text.
|
||||
const words = collectCompactWorkspaceWords(
|
||||
stripDanglingDisplayApostrophes(input),
|
||||
maxWords,
|
||||
STOP_WORDS
|
||||
)
|
||||
return words.map(titleCaseWord).join(' ')
|
||||
}
|
||||
|
||||
function escapeRegExp(input: string): string {
|
||||
|
||||
@@ -58,7 +58,9 @@ describe('wsl login shell command helpers', () => {
|
||||
const command = buildWslLoginShellCommand("printf 'hello'")
|
||||
|
||||
expect(command).toContain('getent passwd')
|
||||
expect(command).toContain('bash|zsh|ksh|mksh|ash)')
|
||||
expect(command).toContain('exec "$_orca_wsl_shell" -ilc')
|
||||
expect(command).toContain('exec /bin/sh -lc')
|
||||
expect(command).toContain("printf '\\''hello'\\''")
|
||||
})
|
||||
|
||||
|
||||
@@ -27,9 +27,11 @@ export function buildWslLoginShellCommand(command: string): string {
|
||||
'if [ -z "$_orca_wsl_shell" ] || [ ! -x "$_orca_wsl_shell" ]; then',
|
||||
' _orca_wsl_shell=/bin/sh',
|
||||
'fi',
|
||||
'case "$(basename "$_orca_wsl_shell")" in',
|
||||
'_orca_wsl_shell_name=$(basename "$_orca_wsl_shell" | tr "[:upper:]" "[:lower:]")',
|
||||
'case "$_orca_wsl_shell_name" in',
|
||||
` sh|dash) exec "$_orca_wsl_shell" -lc ${quotedCommand} ;;`,
|
||||
` *) exec "$_orca_wsl_shell" -ilc ${quotedCommand} ;;`,
|
||||
` bash|zsh|ksh|mksh|ash) exec "$_orca_wsl_shell" -ilc ${quotedCommand} ;;`,
|
||||
` *) exec /bin/sh -lc ${quotedCommand} ;;`,
|
||||
'esac'
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user