Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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
86 changes: 86 additions & 0 deletions src/commands/focus/focus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import type { LocalCommandResult } from '../../types/command.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()
})
})
22 changes: 22 additions & 0 deletions src/commands/focus/focus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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.',
}
}

const next = !(getGlobalConfig().focusView ?? false)
saveGlobalConfig(current => ({ ...current, focusView: next }))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
37 changes: 30 additions & 7 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,14 @@ 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,
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 +540,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 +563,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 @@ -715,7 +736,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 +838,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
19 changes: 19 additions & 0 deletions src/components/Settings/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,25 @@ 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
}));
setGlobalConfig({
...getGlobalConfig(),
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
2 changes: 2 additions & 0 deletions src/components/messageActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export function isNavigableMessage(msg: NavigableMessage): boolean {
case 'agents_killed':
case 'away_summary':
case 'thinking':
case 'focus_marker':
case 'focus_summary':
return false;
}
return true;
Expand Down
31 changes: 31 additions & 0 deletions src/components/messages/FocusMarkerMessage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as React from 'react'
import { Box, Text } from '../../ink.js'
import { useShortcutDisplay } from '../../keybindings/useShortcutDisplay.js'
import { CompactBoundaryMessage } from './CompactBoundaryMessage.js'

type Props = {
hiddenTurns: number
compacted: boolean
}

export function FocusMarkerMessage({
hiddenTurns,
compacted,
}: Props): React.ReactNode {
const historyShortcut = useShortcutDisplay(
'app:toggleTranscript',
'Global',
'ctrl+o',
)
return (
<Box flexDirection="column">
{hiddenTurns > 0 && (
<Text dimColor>
{hiddenTurns} earlier {hiddenTurns === 1 ? 'turn' : 'turns'} hidden,{' '}
{historyShortcut} for transcript, /focus to turn off
</Text>
)}
{compacted && <CompactBoundaryMessage />}
</Box>
)
}
Loading
Loading