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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ describe('builtInCommandNames', () => {
}
})

test('includes the focus command', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'oc-test-focus-'))
try {
const cmds = await getCommands(cwd)
expect(cmds.map(c => c.name)).toContain('focus')
} finally {
await rm(cwd, { recursive: true, force: true })
}
})

test('project skills take precedence over bundled skills with the same name', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'oc-test-skill-precedence-'))
const originalSources = getAllowedSettingSources()
Expand Down
2 changes: 2 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
} from './commands/request-size/index.js'
import resume, { continueCommand } from './commands/resume/index.js'
import review, { ultrareview } from './commands/review.js'
import focus from './commands/focus/index.js'
import scrollSpeed from './commands/scroll-speed/index.js'
import search from './commands/search/index.js'
import session from './commands/session/index.js'
Expand Down Expand Up @@ -354,6 +355,7 @@ const COMMANDS = memoize((): Command[] => [
requestSize,
requestSizeNonInteractive,
resume,
focus,
scrollSpeed,
search,
session,
Expand Down
119 changes: 119 additions & 0 deletions src/commands/focus/focus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'
import type { LocalCommandResult } from '../../types/command.js'
import * as configModule from '../../utils/config.js'
import { getGlobalConfig, saveGlobalConfig } from '../../utils/config.js'
import { _resetTmuxControlModeProbeForTesting } from '../../utils/fullscreen.js'
import { call } from './focus.js'

const noopContext = {} as Parameters<typeof call>[1]

function expectText(
res: LocalCommandResult,
): Extract<LocalCommandResult, { type: 'text' }> {
if (res.type !== 'text') throw new Error(`expected a text result, got ${res.type}`)
return res
}

const ENV_KEYS = ['CLAUDE_CODE_NO_FLICKER', 'TMUX', 'TERM_PROGRAM', 'TERM'] as const
const savedEnv = new Map<string, string | undefined>(
ENV_KEYS.map(k => [k, process.env[k]]),
)

function setFocus(value: boolean | undefined): void {
saveGlobalConfig(current => ({ ...current, focusView: value }))
}

describe('/focus', () => {
beforeEach(() => {
for (const k of ENV_KEYS) delete process.env[k]
process.env.CLAUDE_CODE_NO_FLICKER = '1'
_resetTmuxControlModeProbeForTesting()
setFocus(undefined)
})

afterEach(() => {
setFocus(undefined)
for (const k of ENV_KEYS) {
const v = savedEnv.get(k)
if (v === undefined) delete process.env[k]
else process.env[k] = v
}
_resetTmuxControlModeProbeForTesting()
})

test('turns focus on from off and says so', async () => {
setFocus(false)
const res = expectText(await call('', noopContext))
expect(getGlobalConfig().focusView).toBe(true)
expect(res.value).toContain('Focus view is on')
})

test('turns focus on when the setting was never stored', async () => {
const res = expectText(await call('', noopContext))
expect(getGlobalConfig().focusView).toBe(true)
expect(res.value).toContain('Focus view is on')
})

test('turns focus off from on and says so', async () => {
setFocus(true)
const res = expectText(await call('', noopContext))
expect(getGlobalConfig().focusView).toBe(false)
expect(res.value).toContain('Focus view is off')
})

test('ignores arguments: "on" with focus already on still toggles off', async () => {
setFocus(true)
const res = expectText(await call('on', noopContext))
expect(getGlobalConfig().focusView).toBe(false)
expect(res.value).toContain('Focus view is off')
})

for (const start of [false, true]) {
test(`outside fullscreen it points to /tui fullscreen and leaves focus ${start}`, async () => {
process.env.CLAUDE_CODE_NO_FLICKER = '0'
setFocus(start)
const res = expectText(await call('', noopContext))
expect(res.value).toContain('/tui fullscreen')
expect(getGlobalConfig().focusView).toBe(start)
})
}

test('outside fullscreen it leaves an unset setting unset', async () => {
process.env.CLAUDE_CODE_NO_FLICKER = '0'
const res = expectText(await call('', noopContext))
expect(res.value).toContain('/tui fullscreen')
expect(getGlobalConfig().focusView).toBeUndefined()
})

test('toggles against the config the locked updater sees, not a stale cached read', async () => {
setFocus(true)
// Another session already turned focus on; this session's cache still says off.
const stale = spyOn(configModule, 'getGlobalConfig').mockReturnValue({
...getGlobalConfig(),
focusView: false,
})
try {
const res = expectText(await call('', noopContext))
stale.mockRestore()
expect(getGlobalConfig().focusView).toBe(false)
expect(res.value).toContain('Focus view is off')
} finally {
stale.mockRestore()
}
})

test('does not report success when the write was skipped', async () => {
setFocus(false)
const skipped = spyOn(configModule, 'saveGlobalConfig').mockImplementation(
() => {},
)
try {
const res = expectText(await call('', noopContext))
expect(getGlobalConfig().focusView).toBe(false)
expect(res.value).not.toContain('Focus view is on')
expect(res.value).toContain('Could not save')
} finally {
skipped.mockRestore()
}
})
})
37 changes: 37 additions & 0 deletions src/commands/focus/focus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { LocalCommandCall } from '../../types/command.js'
import { getGlobalConfig, saveGlobalConfig } from '../../utils/config.js'
import { isFullscreenEnvEnabled } from '../../utils/fullscreen.js'

export const call: LocalCommandCall = async () => {
if (!isFullscreenEnvEnabled()) {
return {
type: 'text',
value:
'Focus view needs the fullscreen display mode. Run /tui fullscreen first.',
}
}

// Derive the inverse from the config the locked updater receives: the cached
// read can lag a write another session just made.
let next = false
let ran = false
saveGlobalConfig(current => {
ran = true
next = !(current.focusView ?? false)
return { ...current, focusView: next }
})
// saveGlobalConfig returns without throwing when it skips a write (permission
// error, auth guard), so confirm the stored value before reporting.
if (!ran || (getGlobalConfig().focusView ?? false) !== next) {
return {
type: 'text',
value: 'Could not save the focus view setting. Check write access to the config file.',
}
}
return {
type: 'text',
value: next
? 'Focus view is on. Only your latest prompt, a tool summary and the response show.'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
: 'Focus view is off.',
}
}
11 changes: 11 additions & 0 deletions src/commands/focus/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Command } from '../../commands.js'

const focus = {
type: 'local',
name: 'focus',
description: 'Toggle focus view (latest prompt, tool summary and response)',
supportsNonInteractive: false,
load: () => import('./focus.js'),
} satisfies Command

export default focus
8 changes: 8 additions & 0 deletions src/components/Message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import { AssistantToolUseMessage } from './messages/AssistantToolUseMessage.js';
import { AttachmentMessage } from './messages/AttachmentMessage.js';
import { CollapsedReadSearchContent } from './messages/CollapsedReadSearchContent.js';
import { CompactBoundaryMessage } from './messages/CompactBoundaryMessage.js';
import { FocusMarkerMessage } from './messages/FocusMarkerMessage.js';
import { FocusSummaryMessage } from './messages/FocusSummaryMessage.js';
import { GroupedToolUseContent } from './messages/GroupedToolUseContent.js';
import { SystemTextMessage } from './messages/SystemTextMessage.js';
import { UserImageMessage } from './messages/UserImageMessage.js';
Expand Down Expand Up @@ -243,6 +245,12 @@ function MessageImpl(t0: Props) {
}
return t2;
}
if (message.subtype === "focus_marker") {
return <FocusMarkerMessage hiddenTurns={message.hiddenTurns} compacted={message.compacted} />;
}
if (message.subtype === "focus_summary") {
return <FocusSummaryMessage summary={message.summary} />;
}
if (message.subtype === "microcompact_boundary") {
return null;
}
Expand Down
40 changes: 32 additions & 8 deletions src/components/Messages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { collapseReadSearchGroups } from '../utils/collapseReadSearch.js';
import { collapseTeammateShutdowns } from '../utils/collapseTeammateShutdowns.js';
import { getGlobalConfig } from '../utils/config.js';
import { isEnvTruthy } from '../utils/envUtils.js';
import { assembleFocusRows, selectFocusView } from '../utils/focusView.js';
import { isFullscreenEnvEnabled } from '../utils/fullscreen.js';
import { applyGrouping } from '../utils/groupToolUses.js';
import { buildMessageLookups, createAssistantMessage, deriveUUID, getMessagesAfterCompactBoundary, getToolUseID, getToolUseIDs, hasUnresolvedHooksFromLookup, isNotEmptyMessage, normalizeMessages, normalizeMessagesCached, reorderMessagesInUI, type StreamingThinking, type StreamingToolUse, shouldShowUserMessage } from '../utils/messages.js';
Expand Down Expand Up @@ -235,6 +236,8 @@ type Props = {
streamingText?: string | null;
/** When true, only show Brief tool output (hide everything else) */
isBriefOnly?: boolean;
/** Fullscreen focus view: show only the latest prompt, a tool summary and the final response. */
isFocusView?: boolean;
/** Fullscreen-mode "─── N new ───" divider. Renders before the first
* renderableMessage derived from firstUnseenUuid (matched by the 24-char
* prefix that deriveUUID preserves). */
Expand Down Expand Up @@ -360,6 +363,7 @@ const MessagesImpl = ({
streamingThinking,
streamingText,
isBriefOnly = false,
isFocusView = false,
unseenDivider,
scrollRef,
trackStickyPrompt,
Expand Down Expand Up @@ -516,8 +520,15 @@ const MessagesImpl = ({
// assistant text for file-only turns would leave the user with no context.
const dropTextToolNames = [BRIEF_TOOL_NAME].filter((n_0): n_0 is string => n_0 !== null);
const briefFiltered = briefToolNames.length > 0 && !isTranscriptMode ? isBriefOnly ? filterForBriefTool(messagesToShowNotTruncated, briefToolNames) : dropTextToolNames.length > 0 ? dropTextInBriefTurns(messagesToShowNotTruncated, dropTextToolNames) : messagesToShowNotTruncated : messagesToShowNotTruncated;
const messagesToShow = shouldTruncate ? briefFiltered.slice(-MAX_MESSAGES_TO_SHOW_IN_TRANSCRIPT_MODE) : briefFiltered;
const hasTruncatedMessages = shouldTruncate && briefFiltered.length > MAX_MESSAGES_TO_SHOW_IN_TRANSCRIPT_MODE;
// Focus view runs after the brief tier and before truncation and grouping,
// and never in the ctrl+o transcript, which stays unfiltered.
const focusFiltered = isFocusView && !isTranscriptMode ? assembleFocusRows(selectFocusView(briefFiltered, {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
isLoading,
replyToolNames: new Set(dropTextToolNames),
syntheticToolUseIds: new Set(syntheticStreamingToolUseMessages.flatMap(m => m.message.content.flatMap(b => b.type === 'tool_use' ? [b.id] : [])))
})) : briefFiltered;
const messagesToShow = shouldTruncate ? focusFiltered.slice(-MAX_MESSAGES_TO_SHOW_IN_TRANSCRIPT_MODE) : focusFiltered;
const hasTruncatedMessages = shouldTruncate && focusFiltered.length > MAX_MESSAGES_TO_SHOW_IN_TRANSCRIPT_MODE;
const {
messages: groupedMessages
} = applyGrouping(messagesToShow, tools, verbose);
Expand All @@ -530,7 +541,7 @@ const MessagesImpl = ({
hasTruncatedMessages,
hiddenMessageCount
};
}, [verbose, normalizedMessages, isTranscriptMode, syntheticStreamingToolUseMessages, shouldTruncate, tools, isBriefOnly]);
}, [verbose, normalizedMessages, isTranscriptMode, syntheticStreamingToolUseMessages, shouldTruncate, tools, isBriefOnly, isFocusView, isFocusView && isLoading]);

// Cheap slice — only runs when scroll range or slice config changes.
const renderableMessages = useMemo(() => {
Expand All @@ -553,8 +564,19 @@ const MessagesImpl = ({
const dividerBeforeIndex = useMemo(() => {
if (!unseenDivider) return -1;
const prefix = unseenDivider.firstUnseenUuid.slice(0, 24);
return renderableMessages.findIndex(m => m.uuid.slice(0, 24) === prefix);
}, [unseenDivider, renderableMessages]);
const exact = renderableMessages.findIndex(m => m.uuid.slice(0, 24) === prefix);
if (exact >= 0 || !isFocusView) return exact;
// Focus view hides the first unseen message: put the divider before the
// first rendered row that sits at or after it in the full list.
const position = new Map<string, number>();
normalizedMessages.forEach((m, i) => {
const key = m.uuid.slice(0, 24);
if (!position.has(key)) position.set(key, i);
});
const unseenPosition = position.get(prefix);
if (unseenPosition === undefined) return -1;
return renderableMessages.findIndex(m => (position.get(m.uuid.slice(0, 24)) ?? -1) >= unseenPosition);
}, [unseenDivider, renderableMessages, isFocusView, normalizedMessages]);
const selectedIdx = useMemo(() => {
if (!cursor) return -1;
return renderableMessages.findIndex(m_0 => m_0.uuid === cursor.uuid);
Expand Down Expand Up @@ -701,7 +723,7 @@ const MessagesImpl = ({
passing the array would accumulate every historical version
(~1-2MB over a 7-turn session). */}
{virtualScrollRuntimeGate ? <InVirtualListContext.Provider value={true}>
<VirtualMessageList messages={renderableMessages} scrollRef={scrollRef} columns={columns} itemKey={messageKey} renderItem={renderMessageRow} onItemClick={onItemClick} isItemClickable={isItemClickable} isItemExpanded={isItemExpanded} trackStickyPrompt={trackStickyPrompt} selectedIndex={selectedIdx >= 0 ? selectedIdx : undefined} cursorNavRef={cursorNavRef} setCursor={setCursor} jumpRef={jumpRef} onSearchMatchesChange={onSearchMatchesChange} scanElement={scanElement} setPositions={setPositions} extractSearchText={extractSearchText} />
<VirtualMessageList messages={renderableMessages} scrollRef={scrollRef} columns={columns} itemKey={messageKey} renderItem={renderMessageRow} onItemClick={onItemClick} isItemClickable={isItemClickable} isItemExpanded={isItemExpanded} trackStickyPrompt={trackStickyPrompt} selectedIndex={selectedIdx >= 0 ? selectedIdx : undefined} cursorNavRef={cursorNavRef} setCursor={setCursor} jumpRef={jumpRef} onSearchMatchesChange={onSearchMatchesChange} scanElement={scanElement} setPositions={setPositions} extractSearchText={extractSearchText} rekeyOnChange={isFocusView} />
</InVirtualListContext.Provider> : renderableMessages.flatMap(renderMessageRow)}

{streamingText && !isBriefOnly && <Box alignItems="flex-start" flexDirection="row" marginTop={1} width="100%">
Expand All @@ -715,7 +737,7 @@ const MessagesImpl = ({
</Box>
</Box>}

{isStreamingThinkingVisible && streamingThinking && !isBriefOnly && <Box marginTop={1}>
{isStreamingThinkingVisible && streamingThinking && !isBriefOnly && !isFocusView && <Box marginTop={1}>
<AssistantThinkingMessage param={{
type: 'thinking',
thinking: streamingThinking.thinking
Expand Down Expand Up @@ -817,7 +839,9 @@ export function shouldRenderStatically(message: RenderableMessage, streamingTool
{
// api errors always render dynamically, since we hide
// them as soon as we see another non-error message.
return message.subtype !== 'api_error';
// The focus summary updates in place under a stable uuid, so it must
// keep re-rendering.
return message.subtype !== 'api_error' && message.subtype !== 'focus_summary';
}
case 'grouped_tool_use':
{
Expand Down
23 changes: 23 additions & 0 deletions src/components/Settings/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,29 @@ export function Config({
value: String(flickerFreeMode) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
});
}
}, {
id: 'focusView',
label: 'Focus view',
value: globalConfig.focusView ?? false,
type: 'boolean' as const,
onChange(focusView: boolean) {
saveGlobalConfig(current => ({
...current,
focusView
}));
// The save can be skipped (permission error), so show and log what is stored.
const stored = getGlobalConfig().focusView ?? false;
setGlobalConfig({
...getGlobalConfig(),
focusView: stored
});
if (stored === focusView) {
logEvent('tengu_config_changed', {
setting: 'focusView' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
value: String(focusView) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
});
}
}
},
// autoUpdates setting is hidden - use DISABLE_AUTOUPDATER env var to control
autoUpdaterDisabledReason ? {
Expand Down
Loading
Loading