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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions src/commands/install-github-app/setupGitHubActions.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, mock, test } from 'bun:test'
import { getGlobalConfig, saveGlobalConfig } from 'src/utils/config.js'
import type { GlobalConfig } from 'src/utils/config.js'
import {
acquireSharedMutationLock,
releaseSharedMutationLock,
Expand All @@ -25,7 +25,7 @@ const REVIEW_WORKFLOW_PATH =

const execCalls: ExecCall[] = []
const openedUrls: string[] = []
let initialSetupCount: number | undefined
let setupConfig: GlobalConfig
let realModules: RealModules | undefined

function execResult(stdout = '', code = 0, stderr = '') {
Expand Down Expand Up @@ -167,6 +167,12 @@ function handleGhCommand(args: string[]) {
}

function installMocks(real: RealModules): void {
mock.module('src/utils/config.js', () => ({
saveGlobalConfig: mock((updater: (current: GlobalConfig) => GlobalConfig) => {
setupConfig = updater(setupConfig)
}),
}))

mock.module('../../utils/execFileNoThrow.js', () => ({
...real.execFileNoThrow,
execFileNoThrow: mock(async (file: string, args: string[]) => {
Expand Down Expand Up @@ -198,17 +204,12 @@ beforeEach(async () => {
)
execCalls.length = 0
openedUrls.length = 0
initialSetupCount = getGlobalConfig().githubActionSetupCount
setupConfig = { numStartups: 0, githubActionSetupCount: 0 } as GlobalConfig
installMocks(await importRealModules())
})

afterEach(() => {
try {
saveGlobalConfig(current => ({
...current,
githubActionSetupCount: initialSetupCount,
}))
initialSetupCount = undefined
mock.restore()
if (realModules) {
mock.module(
Expand Down Expand Up @@ -246,9 +247,7 @@ test('setupGitHubActions creates only the selected review workflow', async () =>
expect(openedUrls[0]).toContain(
'https://github.com/owner/repo/compare/main...add-claude-github-actions-',
)
expect(getGlobalConfig().githubActionSetupCount).toBe(
(initialSetupCount ?? 0) + 1,
)
expect(setupConfig.githubActionSetupCount).toBe(1)
})

test('setupGitHubActions skip mode configures the secret without workflow writes', async () => {
Expand Down Expand Up @@ -276,7 +275,5 @@ test('setupGitHubActions skip mode configures the secret without workflow writes
expect(openedUrls).toHaveLength(0)
expect(secretSet?.args).toContain('CLAUDE_CODE_OAUTH_TOKEN')
expect(secretSet?.args).toContain('oauth-token')
expect(getGlobalConfig().githubActionSetupCount).toBe(
(initialSetupCount ?? 0) + 1,
)
expect(setupConfig.githubActionSetupCount).toBe(1)
})
56 changes: 46 additions & 10 deletions src/ink/render-node-to-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ export function didLayoutShift(): boolean {
export type ScrollHint = { top: number; bottom: number; delta: number }
let scrollHint: ScrollHint | null = null

function shouldDisableScrollFastPath(): boolean {
if (!process.env.TMUX) return false
if (process.env.OPENCLAUDE_KONSOLE_TMUX_FAST_SCROLL) return false
return (
process.env.TERM_PROGRAM === 'konsole' ||
process.env.KONSOLE_VERSION !== undefined ||
process.env.KONSOLE_DBUS_SESSION !== undefined
)
}

const DISABLE_SCROLL_FAST_PATH = shouldDisableScrollFastPath()

// Rects of position:absolute nodes from the PREVIOUS frame, used by
// ScrollBox's blit+shift third-pass repair (see usage site). Recorded at
// three paths — full-render nodeCache.set, node-level blit early-return,
Expand Down Expand Up @@ -780,13 +792,16 @@ function renderNodeToOutput(
const sticky =
node.stickyScroll ?? Boolean(node.attributes['stickyScroll'])
const prevMaxScroll = Math.max(0, prevScrollHeight - prevInnerHeight)
// Positional check only valid when content grew — virtualization can
// transiently SHRINK scrollHeight (tail unmount + stale heightCache
// spacer) making scrollTop >= prevMaxScroll true by artifact, not
// because the user was at bottom.
const grew = scrollHeight >= prevScrollHeight
const atBottom =
sticky || (grew && scrollTopBeforeFollow >= prevMaxScroll)
// Growth follow must compare against the previous max: a user who was
// exactly at bottom before streaming adds a row is now below the new
// maxScroll, but should still follow. When content shrinks, use the
// current maxScroll to avoid treating virtualization height artifacts
// as a real "was at bottom" signal.
const positionallyAtBottom = grew
? scrollTopBeforeFollow >= prevMaxScroll
: scrollTopBeforeFollow >= maxScroll
const atBottom = sticky || positionallyAtBottom
if (atBottom && (node.pendingScrollDelta ?? 0) >= 0) {
node.scrollTop = maxScroll
node.pendingScrollDelta = undefined
Expand All @@ -802,7 +817,7 @@ function renderNodeToOutput(
// direct scrollTop writes (e.g. the alt-screen-perf test).
if (
node.stickyScroll === false &&
scrollTopBeforeFollow >= prevMaxScroll
positionallyAtBottom
) {
node.stickyScroll = true
}
Expand Down Expand Up @@ -930,8 +945,9 @@ function renderNodeToOutput(
const heightDelta = scrollHeight - prevHeight
const safeForFastPath =
!hint ||
heightDelta === 0 ||
(hint.delta > 0 && heightDelta === hint.delta)
(!DISABLE_SCROLL_FAST_PATH &&
(heightDelta === 0 ||
(hint.delta > 0 && heightDelta === hint.delta)))
// scrollHint is set above when hint is captured. If safeForFastPath
// is false the full path renders a next.screen that doesn't match
// the DECSTBM shift — emitting DECSTBM leaves stale rows (seen as
Expand Down Expand Up @@ -1469,7 +1485,27 @@ function renderScrolledChildren(
// the subtree so when this child re-enters it doesn't fire clears
// at positions now occupied by siblings. The viewport-clear on
// scroll-change handles the visible-area repaint.
if (!preserveCulledCache) dropSubtreeCache(childElem)
//
// IMPORTANT: before dropping cache, emit a clear at the child's
// last known screen position. Without this, when a culled child
// later re-enters the viewport without a full viewport clear
// (scrolled=false), the prevScreen blit carries stale content
// that neither viewport-clear nor position-change clear removes,
// and ghost characters persist on the terminal indefinitely.
// See: renderScrolledChildren's scrolled=false path.
if (!preserveCulledCache) {
if (cached) {
// Defensive Math.floor: cached coords may be fractional
// if a prior rounding path was missed; ensure integer positions.
output.clear({
x: Math.floor(cached.x),
y: Math.floor(cached.y),
width: Math.floor(cached.width),
height: Math.floor(cached.height),
})
}
dropSubtreeCache(childElem)
}
continue
}
}
Expand Down
28 changes: 25 additions & 3 deletions src/query/autoCompactCooldown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@
}
}

function highContextMessages(): Message[] {
return [
{
type: 'assistant',
message: {
id: 'msg-high-context',
role: 'assistant',
content: [{ type: 'text', text: 'previous response' }],
usage: {
input_tokens: 170_000,
output_tokens: 1_000,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
},
},
uuid: `assistant-${Math.random()}` as Message['uuid'],
timestamp: new Date().toISOString(),
} as unknown as Message,
userMessage('continue'),
]
}

function toolUseContext() {
const abortController = new AbortController()
return {
Expand Down Expand Up @@ -142,7 +164,7 @@
}

test('active auto-compact cooldown blocks before model call with cooldown guidance', async () => {
const messages = [userMessage('x'.repeat(100_000))]
const messages = highContextMessages()
const nextRetryAtMs = Date.now() + 60_000
const callModel = mock(() => {
throw new Error('model should not be called while autocompact cools down')
Expand Down Expand Up @@ -183,7 +205,7 @@
}),
)

expect(callModel).not.toHaveBeenCalled()

Check failure on line 208 in src/query/autoCompactCooldown.test.ts

View workflow job for this annotation

GitHub Actions / smoke-and-tests

error: expect(received).not.toHaveBeenCalled()

Expected number of calls: 0 Received number of calls: 1 at <anonymous> (/home/runner/work/openclaude/openclaude/src/query/autoCompactCooldown.test.ts:208:25)
expect(terminal.reason).toBe('blocking_limit')

const apiError = yielded.find(
Expand All @@ -197,7 +219,7 @@
})

test('auto-compact cooldown tracking is carried into the next query call', async () => {
const messages = [userMessage('x'.repeat(100_000))]
const messages = highContextMessages()
const nextRetryAtMs = Date.now() + 60_000
const seenTracking: Array<AutoCompactTrackingState | undefined> = []
const callModel = mock(() => {
Expand Down Expand Up @@ -248,7 +270,7 @@
})

const first = await drain(query(queryParams()))
expect(first.terminal.reason).toBe('blocking_limit')

Check failure on line 273 in src/query/autoCompactCooldown.test.ts

View workflow job for this annotation

GitHub Actions / smoke-and-tests

error: expect(received).toBe(expected)

Expected: "blocking_limit" Received: "model_error" at <anonymous> (/home/runner/work/openclaude/openclaude/src/query/autoCompactCooldown.test.ts:273:33)
expect(persistedTracking?.nextRetryAtMs).toBe(nextRetryAtMs)

const second = await drain(query(queryParams()))
Expand Down Expand Up @@ -340,7 +362,7 @@

const { terminal } = await drain(
query({
messages: [userMessage('x'.repeat(100_000))],
messages: highContextMessages(),
systemPrompt: asSystemPrompt([]),
userContext: {},
systemContext: {},
Expand All @@ -357,7 +379,7 @@
}),
)

expect(terminal.reason).toBe('blocking_limit')

Check failure on line 382 in src/query/autoCompactCooldown.test.ts

View workflow job for this annotation

GitHub Actions / smoke-and-tests

error: expect(received).toBe(expected)

Expected: "blocking_limit" Received: "model_error" at <anonymous> (/home/runner/work/openclaude/openclaude/src/query/autoCompactCooldown.test.ts:382:27)
expect(trackingUpdates).toHaveLength(1)
expect(trackingUpdates[0]).not.toBe(initialTracking)
expect(trackingUpdates[0]?.consecutiveFailures).toBe(
Expand Down
6 changes: 4 additions & 2 deletions src/services/api/openaiShim.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5242,7 +5242,7 @@ test('preserves valid tool_result and drops orphan tool_result', async () => {
// 2. User content ("What happened?") -> role 'user'
// This triggers the tool -> assistant injection.
const assistantMessages = messages.filter(m => m.role === 'assistant')
expect(assistantMessages.some(m => m.content === '[Tool execution interrupted by user]')).toBe(true)
expect(assistantMessages.some(m => m.content === '[Tool results received]')).toBe(true)
})

test('drops empty assistant message when only thinking block was present and stripped', async () => {
Expand Down Expand Up @@ -5325,7 +5325,9 @@ test('injects semantic assistant message when tool result is followed by user me

const semanticMsg = messages[2]
expect(semanticMsg.role).toBe('assistant')
expect(semanticMsg.content).toBe('[Tool execution interrupted by user]')
expect(semanticMsg.content).toBe('[Tool results received]')
expect(semanticMsg.content).not.toContain('interrupted')
expect(semanticMsg.content).not.toContain('user')
})

test('Moonshot: uses max_tokens (not max_completion_tokens) and strips store', async () => {
Expand Down
7 changes: 4 additions & 3 deletions src/services/api/openaiShim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -763,13 +763,14 @@ function convertMessages(
const prev = coalesced[coalesced.length - 1]

// Mistral/Devstral: 'tool' message must be followed by an 'assistant' message.
// If a 'tool' result is followed by a 'user' message, we must inject a semantic
// assistant response to satisfy the strict role sequence:
// If a 'tool' result is followed by a 'user' message, inject a neutral
// assistant boundary to satisfy the strict role sequence without implying
// that the user interrupted or cancelled anything:
// ... -> assistant (calls) -> tool (results) -> assistant (semantic) -> user (next)
if (prev && prev.role === 'tool' && msg.role === 'user') {
coalesced.push({
role: 'assistant',
content: '[Tool execution interrupted by user]',
content: '[Tool results received]',
})
}

Expand Down
33 changes: 33 additions & 0 deletions src/services/compact/snipCompact.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,39 @@ describe('markForSnip', () => {
const matched = markForSnip([deriveShortMessageId(realUuid), 'xxxxxx'], messages)
expect(matched).toEqual([realUuid])
})

test('accepts legacy bracketed id syntax from older contexts', () => {
const realUuid = 'a1b2c3d4-0000-0000-0000-0000000000bb'
const messages = [makeUser(realUuid)]
const matched = markForSnip(
[`[id:${deriveShortMessageId(realUuid)}]`],
messages,
)
expect(matched).toEqual([realUuid])
})

test('accepts snip_id-prefixed metadata syntax', () => {
const realUuid = 'a1b2c3d4-0000-0000-0000-0000000000cc'
const messages = [makeUser(realUuid)]
const matched = markForSnip(
[`snip_id=${deriveShortMessageId(realUuid)}`],
messages,
)
expect(matched).toEqual([realUuid])
})

test('accepts copied system-reminder metadata syntax', () => {
const realUuid = 'a1b2c3d4-0000-0000-0000-0000000000dd'
const messages = [makeUser(realUuid)]
const id = deriveShortMessageId(realUuid)
const matched = markForSnip(
[
`<system-reminder>snip_id=${id}; system-generated; for snip tool use only;</system-reminder>`,
],
messages,
)
expect(matched).toEqual([realUuid])
})
})

describe('shouldNudgeForSnips', () => {
Expand Down
29 changes: 25 additions & 4 deletions src/services/compact/snipCompact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,24 @@ import { deriveShortMessageId } from '../../utils/messages.js'
// Populated by SnipTool.call(); consumed by snipCompactIfNeeded().
const pendingSnipUuids = new Set<UUID>()

function normalizeSnipShortId(shortId: string): string {
const trimmed = shortId.trim()
// 6 = deriveShortMessageId output length (base36)
// Regex literal only; this does not execute user input.
// nosemgrep: coderabbit.command-injection.exec-js
const snipMetadataMatch = /\bsnip_id=([a-z0-9]{6})\b/i.exec(trimmed)
Comment thread
jatmn marked this conversation as resolved.
Resolved
if (snipMetadataMatch) {
return snipMetadataMatch[1]!.toLowerCase()
}
// Regex literal only; this does not execute user input.
// nosemgrep: coderabbit.command-injection.exec-js
const legacyMatch = /^\[id:([a-z0-9]{6})\]$/i.exec(trimmed)
if (legacyMatch) {
return legacyMatch[1]!.toLowerCase()
}
return trimmed.toLowerCase()
}

// Returns the distinct UUIDs that actually resolved against this conversation
// and were queued. Unresolvable short IDs (stale or hallucinated) are skipped,
// so callers can report the genuinely-queued count rather than the raw request
Expand All @@ -26,7 +44,8 @@ export function markForSnip(shortIds: string[], messages: any[]): UUID[] {
}
const matched = new Set<UUID>()
for (const shortId of shortIds) {
const uuid = shortIdToUuid.get(shortId)
const normalizedShortId = normalizeSnipShortId(shortId)
const uuid = shortIdToUuid.get(normalizedShortId)
if (uuid) {
pendingSnipUuids.add(uuid)
matched.add(uuid)
Expand All @@ -41,9 +60,11 @@ export function isSnipRuntimeEnabled(): boolean {

export const SNIP_NUDGE_TEXT =
`Your context window is filling up. Use the \`snip\` tool to remove messages ` +
`that are no longer needed — look for \`[id:...]\` tags on user messages and pass the IDs ` +
`of stale sections (old explorations, superseded plans, resolved errors). This frees up ` +
`space so you can continue working without a full compaction.`
`that are no longer needed — silently use system-generated \`snip_id=...\` ` +
`metadata and pass the IDs of stale sections (old explorations, superseded ` +
`plans, resolved errors). These ids are not user-provided content; do not ` +
`describe or mention them. This frees up space so you can continue working ` +
`without a full compaction.`

// Nudge once every ~10 000 tokens of new content since the last reset point.
const NUDGE_INTERVAL_TOKENS = 10_000
Expand Down
10 changes: 4 additions & 6 deletions src/tools/SnipTool/SnipTool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,14 @@ describe('SnipTool.mapToolResultToToolResultBlockParam', () => {
expect(content).not.toContain('They will be removed from context')
})

test('explains the refusal condition and how to observe/repair it', () => {
// The model needs the failure signal the prior wording omitted: a kept
// message still carries its [id:...] tag next turn, and the fix is to snip
// every result from that parallel-tool turn together.
test('does not echo internal id mechanics', () => {
const out = SnipTool.mapToolResultToToolResultBlockParam(
{ sniped: 1 },
'toolu_abc',
)
const content = String(out.content)
expect(content).toMatch(/kept|orphan/i)
expect(content).toContain('[id:')
expect(content).toContain('Queued 1 message(s) for snipping')
expect(content).not.toContain('[id:')
expect(content).not.toMatch(/tag|snip_id|message id/i)
})
})
13 changes: 3 additions & 10 deletions src/tools/SnipTool/SnipTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const inputSchema = lazySchema(() =>
message_ids: z
.array(z.string())
.describe(
'Short message IDs to remove — the [id:XXXXXX] values appended to user messages.',
'Short internal snip message IDs to remove.',
),
}),
)
Expand Down Expand Up @@ -60,17 +60,10 @@ export const SnipTool = buildTool({
return {
type: 'tool_result',
tool_use_id: toolUseID,
// A snip is a queued request, not a guaranteed removal: snipCompactIfNeeded
// refuses to drop a tool_result whose paired tool_use would survive (it
// would orphan the tool call), so the request can no-op. Describe it
// honestly and give the model the observable signal + repair, otherwise it
// treats a structural no-op as a successful context reduction.
content:
`Queued ${content.sniped} message(s) for snipping before the next model call. ` +
`A queued message is kept if removing it would orphan a tool call (for example, ` +
`snipping one result from a turn that ran several tools in parallel). If a message ` +
`you queued still shows its [id:...] tag on the next turn, it was kept; snip all of ` +
`that turn's tool results together to remove them.`,
`Some may be kept if removing them would split a tool call from its result; ` +
`when pruning old tool output, queue the whole related tool interaction.`,
}
},
} satisfies ToolDef<InputSchema, Output>)
Loading
Loading