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
42 changes: 42 additions & 0 deletions mobile/app/terminal-settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ import { TerminalShortcutSettings } from '../src/components/TerminalShortcutSett
import { setTerminalAutoRestoreFitMsForHost } from '../src/terminal/terminal-auto-restore-fit-state'
import {
loadTerminalAutocompleteEnabled,
loadTerminalDimDirListingSizes,
loadTerminalTextScale,
saveTerminalAutocompleteEnabled,
saveTerminalDimDirListingSizes,
saveTerminalTextScale
} from '../src/storage/preferences'

Expand Down Expand Up @@ -176,6 +178,25 @@ export default function TerminalSettingsScreen() {
void saveTerminalAutocompleteEnabled(next)
}, [])

const [dimDirListingSizes, setDimDirListingSizes] = useState(false)
const userToggledDimSizesRef = useRef(false)
useEffect(() => {
let stale = false
void loadTerminalDimDirListingSizes().then((enabled) => {
if (!stale && !userToggledDimSizesRef.current) {
setDimDirListingSizes(enabled)
}
})
return () => {
stale = true
}
}, [])
const toggleDimDirListingSizes = useCallback((next: boolean) => {
userToggledDimSizesRef.current = true
setDimDirListingSizes(next)
void saveTerminalDimDirListingSizes(next)
}, [])

useEffect(() => {
let cancelled = false
for (const host of hosts) {
Expand Down Expand Up @@ -348,6 +369,27 @@ export default function TerminalSettingsScreen() {
</View>
</View>

<Text style={[styles.groupHeading, styles.inputGroupGap]}>DIRECTORY LISTINGS</Text>
<Text style={styles.groupDescription}>
Dim trailing file-size tokens (1.4K, 738B, …) that coding agents print in directory
listings. Visual only — selection and copy still include the original text. Off by
default.
</Text>
<View style={[styles.section, styles.sectionTopGap]}>
<View style={styles.row}>
<View style={styles.rowContent}>
<Text style={styles.rowLabel}>Dim file sizes</Text>
<Text style={styles.rowSublabel}>{dimDirListingSizes ? 'On' : 'Off'}</Text>
</View>
<Switch
value={dimDirListingSizes}
onValueChange={toggleDimDirListingSizes}
trackColor={{ false: colors.bgRaised, true: colors.textSecondary }}
thumbColor={colors.textPrimary}
/>
</View>
</View>

<TerminalShortcutSettings
scrollRef={scrollRef}
scrollOffsetY={scrollOffsetY}
Expand Down
51 changes: 50 additions & 1 deletion mobile/src/storage/preferences.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ import {
loadHostSidebarWidth,
loadPushNotificationsEnabled,
loadTerminalAutocompleteEnabled,
loadTerminalDimDirListingSizes,
loadTerminalLinkOpenMode,
readPushNotificationsPreference,
readDisabledTerminalLiveInputHandlesPreference,
saveDisabledTerminalLiveInputHandles,
saveHostSidebarWidth,
savePushNotificationsEnabled,
saveTerminalAutocompleteEnabled,
saveTerminalLinkOpenMode
saveTerminalDimDirListingSizes,
saveTerminalLinkOpenMode,
subscribeTerminalDimDirListingSizes
} from './preferences'
import {
loadDefaultSessionView,
Expand Down Expand Up @@ -352,6 +355,52 @@ describe('terminal autocomplete preference', () => {
})
})

describe('terminal dim directory-listing sizes preference', () => {
beforeEach(() => {
vi.mocked(AsyncStorage.getItem).mockReset()
vi.mocked(AsyncStorage.setItem).mockReset()
})

it('defaults to disabled when unset', async () => {
vi.mocked(AsyncStorage.getItem).mockResolvedValue(null)

await expect(loadTerminalDimDirListingSizes()).resolves.toBe(false)
expect(AsyncStorage.getItem).toHaveBeenCalledWith('orca:terminalDimDirListingSizes')
})

it('loads enabled only from the persisted true value', async () => {
vi.mocked(AsyncStorage.getItem).mockResolvedValue('true')
await expect(loadTerminalDimDirListingSizes()).resolves.toBe(true)

vi.mocked(AsyncStorage.getItem).mockResolvedValue('false')
await expect(loadTerminalDimDirListingSizes()).resolves.toBe(false)
})

it('falls back to disabled when storage cannot be read', async () => {
vi.mocked(AsyncStorage.getItem).mockRejectedValue(new Error('storage unavailable'))
await expect(loadTerminalDimDirListingSizes()).resolves.toBe(false)
})

it('persists the selected value and notifies subscribers', async () => {
const seen: boolean[] = []
const unsubscribe = subscribeTerminalDimDirListingSizes((enabled) => {
seen.push(enabled)
})

await saveTerminalDimDirListingSizes(true)
expect(AsyncStorage.setItem).toHaveBeenCalledWith('orca:terminalDimDirListingSizes', 'true')
expect(seen).toEqual([true])

await saveTerminalDimDirListingSizes(false)
expect(AsyncStorage.setItem).toHaveBeenCalledWith('orca:terminalDimDirListingSizes', 'false')
expect(seen).toEqual([true, false])

unsubscribe()
await saveTerminalDimDirListingSizes(true)
expect(seen).toEqual([true, false])
})
})

describe('terminal live input disabled handles preference', () => {
beforeEach(() => {
vi.mocked(AsyncStorage.getItem).mockReset()
Expand Down
31 changes: 31 additions & 0 deletions mobile/src/storage/preferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,37 @@ export async function saveTerminalAutocompleteEnabled(enabled: boolean): Promise
await AsyncStorage.setItem(AUTOCOMPLETE_KEY, String(enabled))
}

const DIM_DIR_LISTING_SIZES_KEY = 'orca:terminalDimDirListingSizes'
type DimDirListingSizesListener = (enabled: boolean) => void
const dimDirListingSizesListeners = new Set<DimDirListingSizesListener>()

// Why: agent directory listings trail spaceless size tokens (1.4K, 738B) that
// crowd phone-width terminals; opt-in visual dim keeps the buffer intact.
export async function loadTerminalDimDirListingSizes(): Promise<boolean> {
try {
const raw = await AsyncStorage.getItem(DIM_DIR_LISTING_SIZES_KEY)
return raw === 'true'
} catch {
return false
}
}

export async function saveTerminalDimDirListingSizes(enabled: boolean): Promise<void> {
await AsyncStorage.setItem(DIM_DIR_LISTING_SIZES_KEY, String(enabled))
for (const listener of dimDirListingSizesListeners) {
listener(enabled)
}
}

export function subscribeTerminalDimDirListingSizes(
listener: DimDirListingSizesListener
): () => void {
dimDirListingSizesListeners.add(listener)
return () => {
dimDirListingSizesListeners.delete(listener)
}
}

const TERMINAL_LIVE_INPUT_DISABLED_PREFIX = 'orca:terminalLiveInputDisabled:'

export type DisabledTerminalLiveInputHandlesPreference = {
Expand Down
24 changes: 24 additions & 0 deletions mobile/src/terminal/TerminalWebView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { createTerminalWebViewPendingMessages } from './terminal-webview-pending
import { dispatchTerminalWebViewNotification } from './terminal-webview-notification-dispatch'
import { routeTerminalQueryReply } from './terminal-webview-query-reply-routing'
import { createTerminalWriteCoalescer } from './terminal-write-coalescer'
import {
loadTerminalDimDirListingSizes,
subscribeTerminalDimDirListingSizes
} from '../storage/preferences'

type Props = TerminalWebViewProps

Expand Down Expand Up @@ -230,6 +234,26 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function
postMessage({ type: 'set-font-scale', fontScale: textScale })
}, [postMessage, textScale])

// Why: settings toggle must dim already-mounted terminals without a reload.
// Subscribe first so a live toggle cannot be overridden by a stale load result.
useEffect(() => {
let cancelled = false
let receivedSubscriptionUpdate = false
const unsubscribe = subscribeTerminalDimDirListingSizes((enabled) => {
receivedSubscriptionUpdate = true
postMessage({ type: 'set-dim-dir-listing-sizes', enabled })
})
void loadTerminalDimDirListingSizes().then((enabled) => {
if (!cancelled && !receivedSubscriptionUpdate) {
postMessage({ type: 'set-dim-dir-listing-sizes', enabled })
}
})
return () => {
cancelled = true
unsubscribe()
}
}, [postMessage])
Comment thread
coderabbitai[bot] marked this conversation as resolved.

useImperativeHandle(
ref,
() => ({
Expand Down
117 changes: 117 additions & 0 deletions mobile/src/terminal/terminal-dir-listing-size-dim-injected.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Visual-only dim of trailing directory-listing size tokens inside the terminal
// WebView. Injected into XTERM_HTML; mirrors matchTrailingDirListingSize in
// terminal-dir-listing-size-dim.ts (unit-tested source of truth).
//
// Decorations overlay the size cells with the terminal background at partial
// opacity so the buffer, selection, and copy stay byte-identical to the PTY.

export const TERMINAL_DIR_LISTING_SIZE_DIM_JS = String.raw`
var dimDirListingSizesEnabled = false;
var sizeDimDecorations = [];
var sizeDimRefreshScheduled = false;
var SIZE_TOKEN_RE = /(\d+(?:\.\d+)?)([KMGT]B?|B)\s*$/i;

function matchTrailingDirListingSize(lineText) {
if (!lineText) return null;
var match = SIZE_TOKEN_RE.exec(lineText);
if (!match || match.index === undefined) return null;
var tokenStart = match.index;
if (tokenStart === 0) return null;
if (!/\s/.test(lineText.charAt(tokenStart - 1))) return null;
var prefixEnd = tokenStart;
while (prefixEnd > 0 && /\s/.test(lineText.charAt(prefixEnd - 1))) prefixEnd -= 1;
if (prefixEnd === 0) return null;
var token = match[1] + match[2];
return { start: tokenStart, end: tokenStart + token.length };
}

function stringIndexToCellCol(line, stringIndex) {
if (!line || stringIndex <= 0) return 0;
var consumed = 0;
for (var col = 0; col < line.length; col++) {
if (consumed >= stringIndex) return col;
var cell = line.getCell(col);
if (!cell) return col;
var chars = cell.getChars();
if (chars) consumed += chars.length;
}
return line.length;
}

function clearSizeDimDecorations() {
for (var i = 0; i < sizeDimDecorations.length; i++) {
// Why: IDecoration.dispose leaves the linked IMarker alive in the buffer.
try { sizeDimDecorations[i].marker.dispose(); } catch (e) {}
try { sizeDimDecorations[i].dispose(); } catch (e) {}
}
sizeDimDecorations = [];
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

function refreshSizeDimDecorations() {
sizeDimRefreshScheduled = false;
clearSizeDimDecorations();
if (!dimDirListingSizesEnabled || !term || typeof term.registerMarker !== 'function') return;
var buf = term.buffer.active;
var baseY = buf.baseY;
var cursorY = buf.cursorY;
// Why: body.style.background is empty when the theme is only set via xterm options.
var bg = (typeof terminalTheme !== 'undefined' && terminalTheme && terminalTheme.background) ||
(typeof defaultTheme !== 'undefined' && defaultTheme.background) ||
'#1a1b26';
for (var row = 0; row < term.rows; row++) {
var absRow = baseY + row;
var line = buf.getLine(absRow);
if (!line) continue;
var text = line.translateToString(false);
var range = matchTrailingDirListingSize(text);
if (!range) continue;
var startCol = stringIndexToCellCol(line, range.start);
var endCol = stringIndexToCellCol(line, range.end);
var width = Math.max(1, endCol - startCol);
var marker;
try {
marker = term.registerMarker(row - cursorY);
} catch (e) {
continue;
}
if (!marker) continue;
var decoration;
try {
decoration = term.registerDecoration({
marker: marker,
x: startCol,
width: width,
layer: 'top'
});
} catch (e) {
try { marker.dispose(); } catch (e2) {}
continue;
}
if (!decoration) {
try { marker.dispose(); } catch (e) {}
continue;
}
decoration.onRender(function (element) {
element.style.background = bg;
element.style.opacity = '0.62';
element.style.pointerEvents = 'none';
});
sizeDimDecorations.push(decoration);
}
}

function scheduleSizeDimRefresh() {
if (!dimDirListingSizesEnabled || sizeDimRefreshScheduled) return;
sizeDimRefreshScheduled = true;
requestAnimationFrame(refreshSizeDimDecorations);
}

function setDimDirListingSizes(enabled) {
dimDirListingSizesEnabled = !!enabled;
if (!dimDirListingSizesEnabled) {
clearSizeDimDecorations();
return;
}
scheduleSizeDimRefresh();
}
`
47 changes: 47 additions & 0 deletions mobile/src/terminal/terminal-dir-listing-size-dim-wiring.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'

const injectedSource = readFileSync(
new URL('./terminal-dir-listing-size-dim-injected.ts', import.meta.url),
'utf8'
)
const webViewSource = readFileSync(new URL('./TerminalWebView.tsx', import.meta.url), 'utf8')
const htmlSource = readFileSync(new URL('./terminal-webview-html.ts', import.meta.url), 'utf8')

describe('dir-listing size dim wiring', () => {
it('disposes the association marker when clearing decorations', () => {
expect(injectedSource).toMatch(
/try\s*\{\s*sizeDimDecorations\[i\]\.marker\.dispose\(\);\s*\}\s*catch/
)
expect(injectedSource).toMatch(/try\s*\{\s*sizeDimDecorations\[i\]\.dispose\(\);\s*\}\s*catch/)
})

it('tints size-dim overlays from terminalTheme.background', () => {
expect(injectedSource).toMatch(/terminalTheme\.background/)
expect(injectedSource).not.toMatch(/document\.body\.style\.background/)
})

it('refreshes size-dim decorations after set-theme', () => {
const setThemeIdx = htmlSource.indexOf("msg.type === 'set-theme'")
expect(setThemeIdx).toBeGreaterThanOrEqual(0)
const nextBranch = htmlSource.indexOf("} else if (msg.type ===", setThemeIdx + 1)
const setThemeBlock = htmlSource.slice(setThemeIdx, nextBranch > setThemeIdx ? nextBranch : undefined)
expect(setThemeBlock).toContain('scheduleSizeDimRefresh')
})

it('subscribes before load so a live toggle is not overridden by a stale initial read', () => {
const effectStart = webViewSource.indexOf(
'settings toggle must dim already-mounted terminals without a reload'
)
expect(effectStart).toBeGreaterThanOrEqual(0)
const effectEnd = webViewSource.indexOf('}, [postMessage])', effectStart)
expect(effectEnd).toBeGreaterThan(effectStart)
const effect = webViewSource.slice(effectStart, effectEnd)
const subscribeIdx = effect.indexOf('subscribeTerminalDimDirListingSizes')
const loadIdx = effect.indexOf('loadTerminalDimDirListingSizes')
expect(subscribeIdx).toBeGreaterThanOrEqual(0)
expect(loadIdx).toBeGreaterThan(subscribeIdx)
expect(effect).toContain('receivedSubscriptionUpdate')
expect(effect).toMatch(/!cancelled\s*&&\s*!receivedSubscriptionUpdate/)
})
})
Loading