feat(cli): refine chat and desktop updates

This commit is contained in:
Siddharth Ganesan committed 2026-08-08 11:36:28 -07:00
1 parent abcc42f829
commit de263204fd
22 files changed
+557 -286

No files matched your search

+2 -2
View File
@@ -17,7 +17,7 @@ concurrency:
jobs:
e2e:
name: E2E (${{ matrix.electron }})
runs-on: macos-14
runs-on: macos-26
strategy:
fail-fast: false
matrix:
@@ -58,7 +58,7 @@ jobs:
package-smoke:
name: Unsigned package smoke
runs-on: macos-14
runs-on: macos-26
steps:
- name: Checkout code
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
+2 -2
View File
@@ -49,7 +49,7 @@ permissions:
jobs:
build-sign-notarize:
name: Build, Sign, Notarize
runs-on: macos-14
runs-on: macos-26
steps:
- name: Checkout code
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
@@ -167,8 +167,8 @@ jobs:
if: ${{ inputs.sign }}
run: |
DMG="$(ls apps/desktop/release/*.dmg | head -1)"
xcrun stapler validate "$DMG"
hdiutil attach "$DMG" -mountpoint /tmp/sim-dmg -nobrowse -quiet
xcrun stapler validate /tmp/sim-dmg/*.app
spctl --assess --type execute --verbose /tmp/sim-dmg/*.app
codesign --verify --deep --strict /tmp/sim-dmg/*.app
hdiutil detach /tmp/sim-dmg -quiet
+14 -2
View File
@@ -1,7 +1,7 @@
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { TERMINAL_DARK_THEME } from '@sim/desktop-bridge'
import { TERMINAL_DARK_THEME, TERMINAL_LIGHT_THEME } from '@sim/desktop-bridge'
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => import('@/test/electron-mock'))
@@ -15,6 +15,14 @@ const IMPORTED_PALETTE = {
...TERMINAL_DARK_THEME,
background: '#101010',
}
const IMPORTED_LIGHT_PALETTE = {
...TERMINAL_LIGHT_THEME,
background: '#fafafa',
}
const IMPORTED_DARK_PALETTE = {
...TERMINAL_DARK_THEME,
background: '#202020',
}
function makeService() {
const config = createConfigStore(
@@ -191,7 +199,7 @@ describe('desktop settings service', () => {
expect(preferences?.browserDownloadDirectory).toBe('/tmp/custom-downloads')
})
it('caches and selects a Terminal or iTerm2 profile', () => {
it('persists a Terminal or iTerm2 profile with appearance-specific palettes', () => {
const { config, service } = makeService()
const preferences = service.selectTerminalProfile({
@@ -199,6 +207,8 @@ describe('desktop settings service', () => {
name: 'Ocean',
source: 'iterm2',
palette: IMPORTED_PALETTE,
lightPalette: IMPORTED_LIGHT_PALETTE,
darkPalette: IMPORTED_DARK_PALETTE,
})
expect(config.get('terminalTheme')).toEqual({
@@ -206,6 +216,8 @@ describe('desktop settings service', () => {
name: 'Ocean',
source: 'iterm2',
palette: IMPORTED_PALETTE,
lightPalette: IMPORTED_LIGHT_PALETTE,
darkPalette: IMPORTED_DARK_PALETTE,
})
expect(preferences).toMatchObject({
terminalTheme: { id: 'iterm2:ocean', name: 'Ocean' },
+2 -6
View File
@@ -1,5 +1,6 @@
import { isAbsolute } from 'node:path'
import {
cloneTerminalSelectedProfile,
type DesktopAppearanceTheme,
type DesktopNotificationPayload,
type DesktopPreferenceKey,
@@ -177,12 +178,7 @@ export function createDesktopSettingsService(
return read()
},
selectTerminalProfile(profile) {
deps.config.set('terminalTheme', {
id: profile.id,
name: profile.name,
source: profile.source,
palette: { ...profile.palette },
})
deps.config.set('terminalTheme', cloneTerminalSelectedProfile(profile))
deps.config.flush()
return read()
},
+17 -1
View File
@@ -1,4 +1,4 @@
import { TERMINAL_DARK_THEME } from '@sim/desktop-bridge'
import { TERMINAL_DARK_THEME, TERMINAL_LIGHT_THEME } from '@sim/desktop-bridge'
import { describe, expect, it } from 'vitest'
import { parseTerminalThemeProfiles } from '@/main/terminal-themes'
@@ -6,6 +6,10 @@ const PALETTE = {
...TERMINAL_DARK_THEME,
background: '#101010',
}
const LIGHT_PALETTE = {
...TERMINAL_LIGHT_THEME,
background: '#fafafa',
}
function profile(id: string, overrides: Record<string, unknown> = {}) {
return {
@@ -22,10 +26,22 @@ describe('parseTerminalThemeProfiles', () => {
expect(parseTerminalThemeProfiles([profile('iterm2:ocean')])).toEqual([profile('iterm2:ocean')])
})
it('preserves separate iTerm2 light and dark palettes', () => {
const separateProfile = profile('iterm2:ocean', {
lightPalette: LIGHT_PALETTE,
darkPalette: PALETTE,
})
expect(parseTerminalThemeProfiles([separateProfile])).toEqual([separateProfile])
})
it('drops malformed colors and unsupported applications', () => {
expect(
parseTerminalThemeProfiles([
profile('bad-color', { palette: { ...PALETTE, background: 'rgb(0, 0, 0)' } }),
profile('bad-mode-color', {
lightPalette: { ...LIGHT_PALETTE, foreground: 'white' },
}),
profile('bad-source', { source: 'warp' }),
])
).toEqual([])
+24 -19
View File
@@ -1,6 +1,7 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import {
cloneTerminalSelectedProfile,
isTerminalSelectedProfile,
TERMINAL_DARK_THEME,
TERMINAL_LIGHT_THEME,
@@ -86,21 +87,25 @@ function terminalPalette(profile) {
return palette
}
function itermPalette(profile) {
const background = dictionaryColor(profile['Background Color'], LIGHT_THEME.background)
function itermColor(profile, key, suffix, fallback) {
return dictionaryColor(profile[key + suffix], dictionaryColor(profile[key], fallback))
}
function itermPalette(profile, suffix) {
const background = itermColor(profile, 'Background Color', suffix, LIGHT_THEME.background)
const dark = isDark(background)
const fallback = dark ? DARK_THEME : LIGHT_THEME
const palette = {
background: background,
foreground: dictionaryColor(profile['Foreground Color'], fallback.foreground),
cursor: dictionaryColor(profile['Cursor Color'], fallback.cursor),
cursorAccent: dictionaryColor(profile['Cursor Text Color'], background),
selectionBackground: dictionaryColor(profile['Selection Color'], fallback.selectionBackground),
selectionForeground: dictionaryColor(profile['Selected Text Color'], fallback.foreground)
foreground: itermColor(profile, 'Foreground Color', suffix, fallback.foreground),
cursor: itermColor(profile, 'Cursor Color', suffix, fallback.cursor),
cursorAccent: itermColor(profile, 'Cursor Text Color', suffix, background),
selectionBackground: itermColor(profile, 'Selection Color', suffix, fallback.selectionBackground),
selectionForeground: itermColor(profile, 'Selected Text Color', suffix, fallback.foreground)
}
for (let index = 0; index < PALETTE_KEYS.length; index += 1) {
const key = PALETTE_KEYS[index]
palette[key] = dictionaryColor(profile['Ansi ' + index + ' Color'], fallback[key])
palette[key] = itermColor(profile, 'Ansi ' + index + ' Color', suffix, fallback[key])
}
return palette
}
@@ -131,12 +136,18 @@ try {
const guid = String(profile.Guid || '')
const name = String(profile.Name || '')
if (!guid || !name) continue
profiles.push({
const result = {
id: 'iterm2:' + encodeURIComponent(guid),
name: name,
source: 'iterm2',
palette: itermPalette(profile)
})
palette: itermPalette(profile, '')
}
const separateColors = profile['Use Separate Colors for Light and Dark Mode']
if (separateColors === true || separateColors === 1) {
result.lightPalette = itermPalette(profile, ' (Light)')
result.darkPalette = itermPalette(profile, ' (Dark)')
}
profiles.push(result)
}
} catch (_) {}
@@ -151,12 +162,7 @@ export function parseTerminalThemeProfiles(value: unknown): TerminalThemeProfile
for (const candidate of value) {
if (!isTerminalSelectedProfile(candidate) || seen.has(candidate.id)) continue
seen.add(candidate.id)
profiles.push({
id: candidate.id,
name: candidate.name,
source: candidate.source,
palette: { ...candidate.palette },
})
profiles.push(cloneTerminalSelectedProfile(candidate))
}
return profiles.sort(
(left, right) => left.source.localeCompare(right.source) || left.name.localeCompare(right.name)
@@ -180,9 +186,8 @@ async function readTerminalThemeProfiles(): Promise<TerminalThemeProfile[]> {
let cachedProfiles: TerminalThemeProfile[] | null = null
let profileLoad: Promise<TerminalThemeProfile[]> | null = null
/** Reads Terminal.app and iTerm2 profiles once per desktop process. */
/** Reads current Terminal.app and iTerm2 profiles, coalescing concurrent requests. */
export async function listTerminalThemeProfiles(): Promise<TerminalThemeProfile[]> {
if (cachedProfiles) return cachedProfiles
profileLoad ??= readTerminalThemeProfiles()
.then((profiles) => {
cachedProfiles = profiles
+28
View File
@@ -25,6 +25,7 @@ import {
isNewerVersion,
parseSemver,
resolveUpdateChannel,
updateCheckIntervalMs,
} from '@/main/updater'
describe('resolveUpdateChannel', () => {
@@ -39,6 +40,17 @@ describe('resolveUpdateChannel', () => {
})
})
describe('updateCheckIntervalMs', () => {
it('checks dev and staging builds every five minutes', () => {
expect(updateCheckIntervalMs('1.2.3-alpha.2')).toBe(5 * 60 * 1000)
expect(updateCheckIntervalMs('1.2.3-beta.1')).toBe(5 * 60 * 1000)
})
it('checks production builds every thirty minutes', () => {
expect(updateCheckIntervalMs('1.2.3')).toBe(30 * 60 * 1000)
})
})
describe('parseSemver', () => {
it('parses plain and v-prefixed versions', () => {
expect(parseSemver('1.2.3')).toEqual({ major: 1, minor: 2, patch: 3, prerelease: '' })
@@ -262,6 +274,22 @@ describe('initUpdater state machine', () => {
vi.mocked(app.getVersion).mockReturnValue('1.0.0')
}
})
it.each([
['1.0.1-alpha.7', 5 * 60 * 1000],
['1.0.1-beta.7', 5 * 60 * 1000],
['1.0.1', 30 * 60 * 1000],
])('schedules %s update polling every %i milliseconds', async (version, interval) => {
vi.mocked(app.getVersion).mockReturnValue(version)
const intervalSpy = vi.spyOn(globalThis, 'setInterval')
try {
await createUpdater({ feedAvailable: true })
expect(intervalSpy).toHaveBeenCalledWith(expect.any(Function), interval)
} finally {
intervalSpy.mockRestore()
vi.mocked(app.getVersion).mockReturnValue('1.0.0')
}
})
})
function manifest(version: string): string {
+12 -3
View File
@@ -10,7 +10,8 @@ import type { EventRecorder } from '@/main/observability'
const logger = createLogger('DesktopUpdater')
const INITIAL_CHECK_DELAY_MS = 10_000
const CHECK_INTERVAL_MS = 4 * 60 * 60 * 1000
const PRERELEASE_CHECK_INTERVAL_MS = 5 * 60 * 1000
const STABLE_CHECK_INTERVAL_MS = 30 * 60 * 1000
export type UpdateChannel = 'latest' | 'beta' | 'alpha'
@@ -72,6 +73,13 @@ export function resolveUpdateChannel(version: string): UpdateChannel {
return 'latest'
}
/** Dev/staging shells poll rapidly; production shells use a quieter cadence. */
export function updateCheckIntervalMs(version: string): number {
return resolveUpdateChannel(version) === 'latest'
? STABLE_CHECK_INTERVAL_MS
: PRERELEASE_CHECK_INTERVAL_MS
}
interface ParsedSemver {
major: number
minor: number
@@ -263,7 +271,8 @@ interface UpdateEngine {
/**
* Keeps installed shells current against the per-environment update feed:
* checks on launch and every four hours, and mirrors pipeline state to the
* checks on launch, then every five minutes for dev/staging builds or every
* thirty minutes for production builds, and mirrors pipeline state to the
* renderer for the settings update UI and the minimum-shell-version gate.
*
* Developer-ID-signed builds use electron-updater (background download,
@@ -528,7 +537,7 @@ export function initUpdater(deps: UpdaterDeps): UpdaterHandle {
}
const check = () => engine?.check()
setTimeout(check, INITIAL_CHECK_DELAY_MS)
setInterval(check, CHECK_INTERVAL_MS)
setInterval(check, updateCheckIntervalMs(currentVersion))
})
return {
@@ -11,15 +11,11 @@ import {
useState,
} from 'react'
import {
type DesktopAppearanceTheme,
type DesktopZoomAction,
type DesktopZoomPercent,
resolveDesktopZoom,
TERMINAL_DARK_THEME,
TERMINAL_LIGHT_THEME,
type TerminalAppearanceTheme,
type TerminalShortcutCommand,
type TerminalThemePalette,
type TerminalThemeProfile,
} from '@sim/desktop-bridge'
import {
@@ -45,7 +41,8 @@ import { getDesktopBridge } from '@/lib/desktop'
import {
loadDesktopTerminalAppearance,
loadDesktopTerminalThemeProfiles,
resolveDesktopAppearanceTheme,
refreshSelectedTerminalProfile,
resolveTerminalThemePalette,
withSelectedProfile,
} from '@/lib/desktop/appearance'
import { trackPanelFocus } from '@/lib/desktop/panel-focus'
@@ -314,15 +311,7 @@ const TerminalView = memo(function TerminalView({
defaultZoom: DesktopZoomPercent
}) {
const { resolvedTheme } = useTheme()
const profileTheme = typeof appearanceTheme === 'string' ? undefined : appearanceTheme
const builtInTheme: DesktopAppearanceTheme =
typeof appearanceTheme === 'string' ? appearanceTheme : 'app'
const colorScheme = resolveDesktopAppearanceTheme(builtInTheme, resolvedTheme)
const terminalTheme: TerminalThemePalette = profileTheme
? profileTheme.palette
: colorScheme === 'dark'
? TERMINAL_DARK_THEME
: TERMINAL_LIGHT_THEME
const terminalTheme = resolveTerminalThemePalette(appearanceTheme, resolvedTheme)
const hostRef = useRef<HTMLDivElement>(null)
const terminalRef = useRef<Terminal | null>(null)
const fitRef = useRef<FitAddon | null>(null)
@@ -756,26 +745,20 @@ export function TerminalSession({ visible, scopeId }: TerminalSessionProps) {
)
useEffect(() => {
if (!visible) return
let active = true
void loadDesktopTerminalAppearance().then((next) => {
if (!active) return
setAppearanceTheme(next.theme)
setDefaultZoom(next.defaultZoom)
})
void Promise.all([loadDesktopTerminalAppearance(), loadDesktopTerminalThemeProfiles()]).then(
([nextAppearance, nextProfiles]) => {
if (!active) return
setProfiles(nextProfiles)
setAppearanceTheme(refreshSelectedTerminalProfile(nextProfiles, nextAppearance.theme))
setDefaultZoom(nextAppearance.defaultZoom)
}
)
return () => {
active = false
}
}, [])
useEffect(() => {
let active = true
void loadDesktopTerminalThemeProfiles().then((next) => {
if (active) setProfiles(next)
})
return () => {
active = false
}
}, [])
}, [visible])
useEffect(() => {
let active = true
@@ -1,6 +1,6 @@
'use client'
import { lazy, memo, Suspense, useEffect, useMemo, useRef, useState } from 'react'
import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button, PlayOutline, Skeleton, Tooltip, toast } from '@sim/emcn'
import {
Download,
@@ -24,6 +24,7 @@ import {
reportManualRunToolStop,
} from '@/lib/copilot/tools/client/run-tool-execution'
import { canonicalWorkspaceFilePath } from '@/lib/copilot/vfs/path-utils'
import { prefersInPlaceNavigation } from '@/lib/desktop'
import { triggerFileDownload } from '@/lib/uploads/client/download'
import { getFileExtension, getMimeTypeFromExtension } from '@/lib/uploads/utils/file-utils'
import {
@@ -73,6 +74,25 @@ const LOADING_SKELETON = (
</div>
)
/**
* Opens an internal app link the way the host expects: a new browser tab on the
* web, and the current view in the desktop app, whose shell would otherwise turn
* the same-origin `window.open` into a second Sim window.
*/
function useOpenInternalLink() {
const router = useRouter()
return useCallback(
(href: string) => {
if (prefersInPlaceNavigation()) {
router.push(href)
return
}
window.open(href, '_blank')
},
[router]
)
}
interface ResourceContentProps {
workspaceId: string
desktopScopeId: string
@@ -350,6 +370,7 @@ interface EmbeddedWorkflowActionsProps {
}
export function EmbeddedWorkflowActions({ workspaceId, workflowId }: EmbeddedWorkflowActionsProps) {
const openInternalLink = useOpenInternalLink()
const { navigateToSettings } = useSettingsNavigation()
const { data: session } = useSession()
const hostContext = useWorkspaceHostContext()
@@ -404,7 +425,7 @@ export function EmbeddedWorkflowActions({ workspaceId, workflowId }: EmbeddedWor
}
const handleOpenWorkflow = () => {
window.open(`/workspace/${workspaceId}/w/${workflowId}`, '_blank')
openInternalLink(`/workspace/${workspaceId}/w/${workflowId}`)
}
return (
@@ -727,6 +748,7 @@ interface EmbeddedFolderProps {
}
function EmbeddedFolder({ workspaceId, folderId }: EmbeddedFolderProps) {
const openInternalLink = useOpenInternalLink()
const { data: folderList, isPending: isFoldersPending } = useFolders(workspaceId)
const { data: workflowList = [] } = useWorkflows(workspaceId)
@@ -760,7 +782,7 @@ function EmbeddedFolder({ workspaceId, folderId }: EmbeddedFolderProps) {
<button
key={w.id}
type='button'
onClick={() => window.open(`/workspace/${workspaceId}/w/${w.id}`, '_blank')}
onClick={() => openInternalLink(`/workspace/${workspaceId}/w/${w.id}`)}
className='flex items-center gap-2 rounded-[6px] px-3 py-2 text-left transition-colors hover:bg-[var(--surface-4)]'
>
<WorkflowIcon className='size-[14px] flex-shrink-0 text-[var(--text-icon)]' />
+55 -1
View File
@@ -1,4 +1,4 @@
import { TERMINAL_DARK_THEME } from '@sim/desktop-bridge'
import { TERMINAL_DARK_THEME, TERMINAL_LIGHT_THEME } from '@sim/desktop-bridge'
import { afterEach, describe, expect, it, vi } from 'vitest'
const { mockBridge } = vi.hoisted(() => ({ mockBridge: { current: undefined as unknown } }))
@@ -10,7 +10,9 @@ vi.mock('@/lib/desktop', () => ({
import {
loadDesktopTerminalAppearance,
loadDesktopTerminalThemeProfiles,
refreshSelectedTerminalProfile,
resolveDesktopAppearanceTheme,
resolveTerminalThemePalette,
} from './appearance'
afterEach(() => {
@@ -35,6 +37,58 @@ describe('resolveDesktopAppearanceTheme', () => {
})
})
describe('resolveTerminalThemePalette', () => {
const fallbackPalette = { ...TERMINAL_DARK_THEME, background: '#111111' }
const lightPalette = { ...TERMINAL_LIGHT_THEME, background: '#fafafa' }
const darkPalette = { ...TERMINAL_DARK_THEME, background: '#222222' }
const profile = {
id: 'iterm2:ocean',
name: 'Ocean',
source: 'iterm2' as const,
palette: fallbackPalette,
lightPalette,
darkPalette,
}
it('uses an imported profile palette matching Sim appearance', () => {
expect(resolveTerminalThemePalette(profile, 'light')).toBe(lightPalette)
expect(resolveTerminalThemePalette(profile, 'dark')).toBe(darkPalette)
})
it('falls back to the source palette when a profile has no mode-specific colors', () => {
const legacyProfile = { ...profile, lightPalette: undefined, darkPalette: undefined }
expect(resolveTerminalThemePalette(legacyProfile, 'light')).toBe(fallbackPalette)
expect(resolveTerminalThemePalette(legacyProfile, 'dark')).toBe(fallbackPalette)
})
it('keeps built-in Sim themes unchanged', () => {
expect(resolveTerminalThemePalette('light', 'dark')).toBe(TERMINAL_LIGHT_THEME)
expect(resolveTerminalThemePalette('dark', 'light')).toBe(TERMINAL_DARK_THEME)
})
})
describe('refreshSelectedTerminalProfile', () => {
const storedProfile = {
id: 'iterm2:ocean',
name: 'Ocean',
source: 'iterm2' as const,
palette: { ...TERMINAL_DARK_THEME, background: '#111111' },
}
const refreshedProfile = {
...storedProfile,
palette: { ...storedProfile.palette, background: '#222222' },
}
it('uses newly discovered colors for the active source profile', () => {
expect(refreshSelectedTerminalProfile([refreshedProfile], storedProfile)).toBe(refreshedProfile)
})
it('keeps built-in and unavailable profile selections unchanged', () => {
expect(refreshSelectedTerminalProfile([refreshedProfile], 'app')).toBe('app')
expect(refreshSelectedTerminalProfile([], storedProfile)).toBe(storedProfile)
})
})
describe('loadDesktopTerminalAppearance', () => {
it('returns a cached profile selection without waiting for source discovery', async () => {
const selectedProfile = {
+31
View File
@@ -4,7 +4,10 @@ import {
isDesktopAppearanceTheme,
isDesktopZoomPercent,
isTerminalAppearanceTheme,
TERMINAL_DARK_THEME,
TERMINAL_LIGHT_THEME,
type TerminalAppearanceTheme,
type TerminalThemePalette,
type TerminalThemeProfile,
} from '@sim/desktop-bridge'
import { getDesktopBridge } from '@/lib/desktop'
@@ -66,6 +69,15 @@ export function withSelectedProfile(
: profiles
}
/** Replaces a persisted profile snapshot with freshly discovered source colors. */
export function refreshSelectedTerminalProfile(
profiles: TerminalThemeProfile[],
theme: TerminalAppearanceTheme
): TerminalAppearanceTheme {
if (typeof theme === 'string') return theme
return profiles.find(({ id }) => id === theme.id) ?? theme
}
/**
* Resolves `app` against next-themes' raw or resolved value. `system` stays
* meaningful for browser CDP; terminal callers treat it as the light fallback
@@ -78,3 +90,22 @@ export function resolveDesktopAppearanceTheme(
if (preference !== 'app') return preference
return appTheme === 'light' || appTheme === 'dark' || appTheme === 'system' ? appTheme : 'system'
}
/**
* Resolves built-in and imported terminal palettes against Sim's live
* appearance. Imported profiles always follow the app appearance — they carry
* their own colors, so there is no separate preference to pin them to.
*/
export function resolveTerminalThemePalette(
theme: TerminalAppearanceTheme,
appTheme: string | undefined
): TerminalThemePalette {
if (typeof theme !== 'string') {
return resolveDesktopAppearanceTheme('app', appTheme) === 'dark'
? (theme.darkPalette ?? theme.palette)
: (theme.lightPalette ?? theme.palette)
}
return resolveDesktopAppearanceTheme(theme, appTheme) === 'dark'
? TERMINAL_DARK_THEME
: TERMINAL_LIGHT_THEME
}
+10
View File
@@ -55,6 +55,16 @@ export function hasDesktopSettings(): boolean {
return isDesktopApp()
}
/**
* True when an internal link must navigate the current view rather than open a
* second one. The shell has no tab strip, so its window-open policy routes a
* same-origin `window.open` to a full new Sim window — where a browser would
* have added a background tab, the desktop app throws up another window.
*/
export function prefersInPlaceNavigation(): boolean {
return isDesktopApp()
}
/**
* The device switches for the browser and terminal, cached because the chat UI
* reads availability synchronously while the shell only answers over async
+54 -27
View File
@@ -724,7 +724,15 @@ export interface TerminalSelectedProfile {
id: string
name: string
source: TerminalThemeSource
/**
* Palette used when the source does not provide appearance-specific colors.
* Ignored once both `lightPalette` and `darkPalette` are present.
*/
palette: TerminalThemePalette
/** Optional palette used while Sim is in light appearance. */
lightPalette?: TerminalThemePalette
/** Optional palette used while Sim is in dark appearance. */
darkPalette?: TerminalThemePalette
}
export type TerminalThemeProfile = TerminalSelectedProfile
@@ -737,41 +745,60 @@ const TERMINAL_THEME_PALETTE_KEYS: readonly (keyof TerminalThemePalette)[] = [
...TERMINAL_THEME_ANSI_KEYS,
]
const TERMINAL_THEME_OPTIONAL_PALETTE_KEYS = ['cursorAccent', 'selectionForeground'] as const
const TERMINAL_THEME_COLOR_PATTERN = /^#[0-9a-f]{6}$/i
function isTerminalThemeColor(value: unknown): value is string {
return typeof value === 'string' && TERMINAL_THEME_COLOR_PATTERN.test(value)
}
function isTerminalThemePalette(value: unknown): value is TerminalThemePalette {
if (typeof value !== 'object' || value === null) return false
const palette = value as Partial<TerminalThemePalette>
return (
TERMINAL_THEME_PALETTE_KEYS.every((key) => isTerminalThemeColor(palette[key])) &&
TERMINAL_THEME_OPTIONAL_PALETTE_KEYS.every(
(key) => palette[key] === undefined || isTerminalThemeColor(palette[key])
)
)
}
export function isTerminalSelectedProfile(value: unknown): value is TerminalSelectedProfile {
if (typeof value !== 'object' || value === null) return false
const candidate = value as Partial<TerminalSelectedProfile>
if (
typeof candidate.id !== 'string' ||
candidate.id.length === 0 ||
candidate.id.length > 300 ||
typeof candidate.name !== 'string' ||
candidate.name.length === 0 ||
candidate.name.length > 200 ||
(candidate.source !== 'terminal' && candidate.source !== 'iterm2') ||
typeof candidate.palette !== 'object' ||
candidate.palette === null
) {
return false
}
if (
!TERMINAL_THEME_PALETTE_KEYS.every(
(key) =>
typeof candidate.palette?.[key] === 'string' &&
TERMINAL_THEME_COLOR_PATTERN.test(candidate.palette[key])
)
) {
return false
}
return (['cursorAccent', 'selectionForeground'] as const).every(
(key) =>
candidate.palette?.[key] === undefined ||
(typeof candidate.palette[key] === 'string' &&
TERMINAL_THEME_COLOR_PATTERN.test(candidate.palette[key]))
return (
typeof candidate.id === 'string' &&
candidate.id.length > 0 &&
candidate.id.length <= 300 &&
typeof candidate.name === 'string' &&
candidate.name.length > 0 &&
candidate.name.length <= 200 &&
(candidate.source === 'terminal' || candidate.source === 'iterm2') &&
isTerminalThemePalette(candidate.palette) &&
(candidate.lightPalette === undefined || isTerminalThemePalette(candidate.lightPalette)) &&
(candidate.darkPalette === undefined || isTerminalThemePalette(candidate.darkPalette))
)
}
/**
* Copies only the known profile fields, so untrusted source output and stored
* config never carry extra keys. The single definition of a profile's shape —
* new palette slots are added here rather than at each call site.
*/
export function cloneTerminalSelectedProfile(
profile: TerminalSelectedProfile
): TerminalSelectedProfile {
return {
id: profile.id,
name: profile.name,
source: profile.source,
palette: { ...profile.palette },
...(profile.lightPalette ? { lightPalette: { ...profile.lightPalette } } : {}),
...(profile.darkPalette ? { darkPalette: { ...profile.darkPalette } } : {}),
}
}
export interface DesktopPreferences {
notificationsEnabled: boolean
notificationSounds: boolean
@@ -4,10 +4,8 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
combineChatAttachments,
existingAttachmentPaths,
loadChatAttachment,
loadChatAttachments,
parseAttachmentPaths,
} from './chat-attachments.js'
const temporaryDirectories: string[] = []
@@ -110,25 +108,3 @@ describe('chat attachments', () => {
)
})
})
describe('attachment path parsing', () => {
it('supports quoted and terminal-escaped paths', () => {
expect(parseAttachmentPaths("'/tmp/one two.md' /tmp/three\\ four.png")).toEqual([
'/tmp/one two.md',
'/tmp/three four.png',
])
expect(() => parseAttachmentPaths("'/tmp/open")).toThrow(/Unclosed quote/)
})
it('recognizes a pasted path containing spaces before trying shell splitting', async () => {
const path = await fixture('a file.txt', 'hello')
await expect(existingAttachmentPaths(path)).resolves.toEqual([path])
await expect(existingAttachmentPaths('this is a normal question')).resolves.toBeNull()
})
it('rejects pasted candidate lists beyond the per-turn limit', async () => {
const candidates = Array.from({ length: 6 }, (_, index) => `/tmp/sim-file-${index}`).join(' ')
await expect(existingAttachmentPaths(candidates)).resolves.toBeNull()
})
})
@@ -205,22 +205,34 @@ export async function loadChatAttachments(paths: string[]): Promise<ChatAttachme
return attachments
}
/** A token from a submitted line, with its span in the original input. */
interface AttachmentToken {
value: string
start: number
end: number
}
/**
* Splits `/attach` input using the subset terminals produce for dragged paths:
* whitespace separation, single/double quotes, and backslash escapes.
* Splits an input line into shell-style tokens, honoring single quotes, double
* quotes and backslash escapes, and keeping each token's span so callers can
* rewrite the original text in place.
*/
export function parseAttachmentPaths(input: string): string[] {
const paths: string[] = []
function tokenizeAttachmentInput(input: string): AttachmentToken[] {
const tokens: AttachmentToken[] = []
let value = ''
let quote: 'single' | 'double' | null = null
let escaped = false
let start = -1
const push = () => {
if (value) paths.push(value)
const push = (end: number) => {
if (value) tokens.push({ value, start, end })
value = ''
start = -1
}
for (const character of input.trim()) {
for (let index = 0; index < input.length; index++) {
const character = input[index] as string
if (start < 0 && !/\s/.test(character)) start = index
if (escaped) {
value += character
escaped = false
@@ -239,7 +251,7 @@ export function parseAttachmentPaths(input: string): string[] {
continue
}
if (/\s/.test(character) && quote === null) {
push()
push(index)
continue
}
value += character
@@ -247,8 +259,8 @@ export function parseAttachmentPaths(input: string): string[] {
if (escaped) value += '\\'
if (quote !== null) throw attachmentError('Unclosed quote in attachment path.')
push()
return paths
push(input.length)
return tokens
}
/**
@@ -259,6 +271,13 @@ export function parseAttachmentPaths(input: string): string[] {
* image and the whole read fails. `loadChatAttachment` caps the size on fstat
* and again on read, which is where the limit belongs anyway.
*/
/** Returns the POSIX path of a file copied in Finder, which carries no text flavor. */
const APPLE_SCRIPT_FILE = [
'on run',
'return POSIX path of (the clipboard as «class furl»)',
'end run',
]
const APPLE_SCRIPT = [
'on run argv',
'set outputPath to item 1 of argv',
@@ -278,9 +297,12 @@ const APPLE_SCRIPT = [
]
/** Best-effort macOS clipboard image extraction, used by the paste keystroke. */
export async function readClipboardImage(): Promise<ChatAttachment | null> {
export async function readClipboardAttachment(): Promise<ChatAttachment | null> {
if (process.platform !== 'darwin') return null
return (await readClipboardImage()) ?? (await readClipboardFile())
}
async function readClipboardImage(): Promise<ChatAttachment | null> {
const directory = await mkdtemp(join(tmpdir(), 'sim-chat-clipboard-'))
const path = join(directory, 'clipboard.png')
try {
@@ -296,29 +318,76 @@ export async function readClipboardImage(): Promise<ChatAttachment | null> {
}
}
/** True when every parsed path names an existing regular file. */
export async function existingAttachmentPaths(input: string): Promise<string[] | null> {
let wholePath
/**
* Reads a file copied in Finder.
*
* The `furl` coercion is lenient — plain clipboard text comes back as a path
* that was never on disk — so the result is only trusted once it stats as a
* real file.
*/
async function readClipboardFile(): Promise<ChatAttachment | null> {
try {
wholePath = await stat(input.trim())
} catch {
wholePath = null
}
if (wholePath?.isFile()) return [input.trim()]
let paths: string[]
try {
paths = parseAttachmentPaths(input)
const args = APPLE_SCRIPT_FILE.flatMap((line) => ['-e', line])
const { stdout } = await execFileAsync('osascript', args, { timeout: 5_000 })
const path = stdout.trim()
if (!path || !(await stat(path)).isFile()) return null
return await loadChatAttachment(path)
} catch {
return null
}
if (paths.length === 0 || paths.length > MAX_CHAT_ATTACHMENTS) return null
for (const path of paths) {
try {
if (!(await stat(path)).isFile()) return null
} catch {
return null
}
}
return paths
}
/** True when every parsed path names an existing regular file. */
async function isFile(path: string): Promise<boolean> {
try {
return (await stat(path)).isFile()
} catch {
return false
}
}
/** Paths found inside a message, and the message with each replaced by a tag. */
export interface ExtractedAttachments {
paths: string[]
text: string
}
/**
* Pulls existing file paths out of a message, wherever they appear.
*
* A token only counts when it resolves to a real file, so prose that merely
* looks path-like — a snippet, a URL fragment — stays literal text. Each match
* is swapped for a `[File #N]` tag so the reader can see what was attached and
* delete it to detach.
*/
export async function extractAttachmentPaths(input: string): Promise<ExtractedAttachments | null> {
/* A path pasted whole may contain unescaped spaces, which tokenizing would
split apart, so the entire line gets the first look. */
const whole = input.trim()
if (whole.includes('/') && (await isFile(whole))) return { paths: [whole], text: '[File #1]' }
let tokens: AttachmentToken[]
try {
tokens = tokenizeAttachmentInput(input)
} catch {
return null
}
const matches: Array<{ token: AttachmentToken; path: string }> = []
for (const token of tokens) {
if (matches.length >= MAX_CHAT_ATTACHMENTS) break
if (!token.value.includes('/') && !token.value.includes('\\')) continue
if (await isFile(token.value)) matches.push({ token, path: token.value })
}
if (matches.length === 0) return null
let text = ''
let cursor = 0
for (const [index, match] of matches.entries()) {
text += `${input.slice(cursor, match.token.start)}[File #${index + 1}]`
cursor = match.token.end
}
text += input.slice(cursor)
return { paths: matches.map((match) => match.path), text: text.trim() }
}
@@ -0,0 +1,77 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { extractAttachmentPaths } from './chat-attachments.js'
let dir: string
let file: string
let spaced: string
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'sim-extract-'))
file = join(dir, 'report.pdf')
spaced = join(dir, 'my report.pdf')
writeFileSync(file, 'x')
writeFileSync(spaced, 'x')
})
afterAll(() => rmSync(dir, { recursive: true, force: true }))
describe('extractAttachmentPaths', () => {
it('pulls a path out of surrounding prose and leaves a tag', async () => {
const result = await extractAttachmentPaths(`summarize ${file} for me`)
expect(result).toEqual({ paths: [file], text: 'summarize [File #1] for me' })
})
it('handles a path at the start or end of the line', async () => {
expect((await extractAttachmentPaths(`${file} what is this`))?.text).toBe(
'[File #1] what is this'
)
expect((await extractAttachmentPaths(`look at ${file}`))?.text).toBe('look at [File #1]')
})
it('numbers multiple attachments in order', async () => {
const result = await extractAttachmentPaths(`diff ${file} against ${file}`)
expect(result?.text).toBe('diff [File #1] against [File #2]')
expect(result?.paths).toHaveLength(2)
})
it('understands quoted and escaped paths with spaces', async () => {
expect((await extractAttachmentPaths(`read "${spaced}" please`))?.paths).toEqual([spaced])
const escaped = spaced.replace(/ /gu, '\\ ')
expect((await extractAttachmentPaths(`read ${escaped} please`))?.paths).toEqual([spaced])
})
it('leaves path-like prose alone when the file does not exist', async () => {
expect(await extractAttachmentPaths('check /nope/missing.png please')).toBeNull()
expect(await extractAttachmentPaths('see src/does-not-exist.ts line 4')).toBeNull()
})
it('attaches a relative path that resolves against the working directory', async () => {
expect((await extractAttachmentPaths('read src/index.ts'))?.paths).toEqual(['src/index.ts'])
})
it('returns null for a message with no paths', async () => {
expect(await extractAttachmentPaths('hello there')).toBeNull()
})
it('takes a whole line that is one unescaped path with spaces', async () => {
expect((await extractAttachmentPaths(` ${spaced} `))?.paths).toEqual([spaced])
})
it('stops at the per-turn attachment limit and leaves the rest as text', async () => {
const line = Array.from({ length: 6 }, () => file).join(' ')
const result = await extractAttachmentPaths(line)
expect(result?.paths).toHaveLength(5)
expect(result?.text).toBe(`[File #1] [File #2] [File #3] [File #4] [File #5] ${file}`)
})
it('keeps the line breaks in a multi-line message', async () => {
const result = await extractAttachmentPaths(`first line\nsummarize ${file}\nlast line`)
expect(result?.text).toBe('first line\nsummarize [File #1]\nlast line')
})
it('does not throw on an unclosed quote', async () => {
expect(await extractAttachmentPaths(`read "${file}`)).toBeNull()
})
})
@@ -184,13 +184,6 @@ export function contextSpans(
/** Composer slash commands, the source for the `/` menu. */
export const SLASH_COMMANDS: SuggestionItem[] = [
{
id: 'attach',
value: '/attach',
displayText: '/attach <paths>',
description: 'attach local files to the next turn',
tag: 'command',
},
{
id: 'clear',
value: '/clear',
@@ -510,7 +510,8 @@ describe('ReadlineChatTerminal', () => {
expect(suggestion).toBeGreaterThanOrEqual(0)
expect(thinking).toBeGreaterThan(suggestion)
expect(thinking).toBe(composer - 2)
expect(thinking).toBe(composer - 3)
expect(lines[composer - 2]).toBe('')
expect(lines[composer - 1]).toBe(' ')
expect(lines[composer + 1]).toBe(' ')
expect(composer + 1).toBe(lines.length - 2)
@@ -523,7 +524,7 @@ describe('ReadlineChatTerminal', () => {
const renderedThinking = renderedLines.findIndex((line) => line?.includes('Thinking…'))
const renderedComposer = renderedLines.findIndex((line) => line?.startsWith(' ❯ /'))
expect(renderedThinking).toBeGreaterThanOrEqual(0)
expect(renderedComposer).toBe(renderedThinking + 2)
expect(renderedComposer).toBe(renderedThinking + 3)
expectUserPanelRow(screen.terminal, renderedComposer - 1, columns)
expectUserPanelRow(screen.terminal, renderedComposer, columns)
expectUserPanelRow(screen.terminal, renderedComposer + 1, columns)
@@ -2028,7 +2029,8 @@ describe('ReadlineChatTerminal', () => {
expect(status).toMatch(/^[·•●] Thinking…$/u)
expect(status).not.toContain('Planning next step')
expect(statusRow).toBeGreaterThanOrEqual(0)
expect(statusRow).toBe(composerRow - 2)
expect(statusRow).toBe(composerRow - 3)
expect(panel[composerRow - 2]).toBe('')
expect(panel[composerRow - 1]).toBe(' ')
expect(panel[composerRow + 1]).toBe(' ')
@@ -15,6 +15,9 @@ import {
truncateDisplay,
} from '../../output/terminal-text.js'
/** Which tag `noteAttachment` writes into the composer. */
export type ChatAttachmentKind = 'Image' | 'File'
export type ChatTerminalInput =
| {
kind: 'line'
@@ -97,8 +100,8 @@ export interface ChatTerminal {
setChatTitle(title: string): void
/** Fills in the workspace name once the lookup resolves. */
setWorkspaceName(name: string): void
/** Inserts an `[Image #N]` tag at the cursor for a just-attached image. */
noteAttachment(): void
/** Inserts an `[Image #N]` or `[File #N]` tag at the cursor for a just-attached file. */
noteAttachment(kind?: ChatAttachmentKind): void
/** Supplies the home-composer `@` resource and `/` skill/MCP pools. */
setSuggestionCandidates?(candidates: ChatSuggestionCandidates): void
/** Clears the visible conversation while preserving the active terminal session. */
@@ -321,7 +324,7 @@ export class ReadlineChatTerminal implements ChatTerminal {
private resourceCandidates: SuggestionItem[] = []
private slashCandidates: SuggestionItem[] = []
private selectedContexts: ChatContext[] = []
private nextAttachmentNumber = 1
private readonly nextAttachmentNumber = new Map<ChatAttachmentKind, number>()
private pasting = false
private pasteBuffer = ''
private pastedText = new Map<number, string>()
@@ -1754,12 +1757,14 @@ export class ReadlineChatTerminal implements ChatTerminal {
/* Keep the suggestion menu visually separate from the activity line. The
composer's shaded top row already separates activity from input. */
const suggestionGap = suggestionRows.length ? [''] : []
const activityGap = activityRows.length ? [''] : []
const composerCursor = {
row:
topMargin.length +
suggestionRows.length +
suggestionGap.length +
activityRows.length +
activityGap.length +
1 +
layout.cursor.row -
firstVisible,
@@ -1771,6 +1776,7 @@ export class ReadlineChatTerminal implements ChatTerminal {
...suggestionRows,
...suggestionGap,
...activityRows,
...activityGap,
userPanelRow(),
...visibleRows.map((line) => userPanelRow(line)),
userPanelRow(),
@@ -2034,8 +2040,10 @@ export class ReadlineChatTerminal implements ChatTerminal {
)}${RESET}\n\n`
}
noteAttachment(): void {
const token = `[Image #${this.nextAttachmentNumber++}]`
noteAttachment(kind: ChatAttachmentKind = 'Image'): void {
const number = this.nextAttachmentNumber.get(kind) ?? 1
this.nextAttachmentNumber.set(kind, number + 1)
const token = `[${kind} #${number}]`
const before = this.draft.slice(0, this.cursor)
const separator = !before || /\s$/u.test(before) ? '' : ' '
this.insertText(`${separator}${token} `)
@@ -2561,11 +2569,11 @@ function cursorTo(row: number, column: number): string {
}
/**
* Spans of `[Image #N]` tags, so a pasted attachment reads as a tag rather than
* loose text. Derived per render like context spans, so deleting the tag stops
* the highlight with no bookkeeping.
* Spans of `[Image #N]` and `[File #N]` tags, so an attachment reads as a tag
* rather than loose text. Derived per render like context spans, so deleting the
* tag stops the highlight with no bookkeeping.
*/
const ATTACHMENT_TOKEN = /\[Image #\d+\]/gu
const ATTACHMENT_TOKEN = /\[(?:Image|File) #\d+\]/gu
function attachmentSpans(text: string): Array<{ start: number; end: number }> {
return [...text.matchAll(ATTACHMENT_TOKEN)].map((match) => ({
@@ -1014,7 +1014,7 @@ describe('interactive chat', () => {
mocks.requestRaw.mockResolvedValueOnce(completed('Retried', 'next-token'))
const terminal = new FakeTerminal(
[
{ kind: 'line', value: '/attach "/private/tmp/notes.txt"' },
{ kind: 'clipboard', value: '' },
{ kind: 'line', value: '/chats' },
{ kind: 'line', value: prompt, display, pastes, contexts },
{ kind: 'line', value: prompt, display, pastes, contexts },
@@ -1027,8 +1027,8 @@ describe('interactive chat', () => {
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
loadAttachments: async (paths) => (paths.length ? [attachment] : []),
pastedAttachmentPaths: async () => null,
clipboardAttachment: async () => attachment,
extractAttachmentPaths: async () => null,
}).parseAsync(['node', 'sim', 'chat'])
expect(detailRequests).toBe(3)
@@ -1413,7 +1413,7 @@ describe('interactive chat', () => {
])
})
it('waits for queued path confirmation before answering a retained question', async () => {
it('attaches a queued path without answering a retained question', async () => {
const question =
'<question>{"type":"single_select","prompt":"Proceed?","options":[{"id":"yes","label":"Yes"}]}</question>'
const attachment: ChatAttachment = {
@@ -1432,7 +1432,6 @@ describe('interactive chat', () => {
queued: true,
display: '/private/tmp/report.txt',
},
{ kind: 'line', value: '/attach "/private/tmp/report.txt"' },
{ kind: 'line', value: '/exit' },
],
[{ kind: 'answer', values: ['Yes'] }]
@@ -1441,21 +1440,18 @@ describe('interactive chat', () => {
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
pastedAttachmentPaths: async (value) =>
value === '/private/tmp/report.txt' ? ['/private/tmp/report.txt'] : null,
extractAttachmentPaths: async (value: string) =>
value === '/private/tmp/report.txt'
? { paths: ['/private/tmp/report.txt'], text: '[File #1]' }
: null,
loadAttachments: async () => [attachment],
}).parseAsync(['node', 'sim', 'chat', 'start'])
expect(terminal.preloads).toContainEqual({
value: '/attach "/private/tmp/report.txt"',
queued: false,
})
expect(terminal.questions).toHaveLength(1)
expect(mocks.requestRaw.mock.calls[1][1].body).toEqual({
workspaceId: 'ws_local',
prompt: 'Proceed? — Yes',
continuationToken: 'token-1',
attachments: [attachment],
})
})
@@ -1549,7 +1545,7 @@ describe('interactive chat', () => {
)
})
it('requires an explicit Enter on a preloaded /attach command for pasted paths', async () => {
it('attaches a pasted path inline and sends the surrounding text', async () => {
const attachment: ChatAttachment = {
name: 'report.txt',
mediaType: 'text/plain',
@@ -1557,58 +1553,55 @@ describe('interactive chat', () => {
}
const absolutePath = '/private/tmp/report.txt'
const terminal = new FakeTerminal([
{ kind: 'line', value: absolutePath },
{ kind: 'line', value: `/attach "${absolutePath}"` },
{ kind: 'line', value: 'Inspect this file' },
{ kind: 'line', value: `Inspect ${absolutePath} closely` },
{ kind: 'line', value: '/exit' },
])
mocks.requestRaw.mockResolvedValue(completed('Done'))
const pastedAttachmentPaths = vi.fn(async (value: string) =>
value === absolutePath ? [absolutePath] : null
const extractAttachmentPaths = vi.fn(async (value: string) =>
value.includes(absolutePath)
? { paths: [absolutePath], text: value.replace(absolutePath, '[File #1]') }
: null
)
const loadAttachments = vi.fn(async (paths: string[]) => (paths.length ? [attachment] : []))
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
pastedAttachmentPaths,
extractAttachmentPaths,
loadAttachments,
}).parseAsync(['node', 'sim', 'chat'])
expect(loadAttachments).toHaveBeenCalledWith([absolutePath])
expect(terminal.reads[1].initialValue).toBe(`/attach "${absolutePath}"`)
expect(terminal.statuses).toContain(
'File path detected. Press Enter to attach it, or edit the command.'
)
expect(terminal.preloads).toEqual([])
expect(terminal.statuses.some((status) => status.startsWith('Unknown command:'))).toBe(false)
expect(mocks.requestRaw.mock.calls[0][1].body).toEqual({
workspaceId: 'ws_local',
prompt: 'Inspect this file',
prompt: 'Inspect [File #1] closely',
attachments: [attachment],
})
})
it('does not read or upload a detected path when confirmation is cancelled', async () => {
it('never reads a path out of a slash command', async () => {
const absolutePath = '/private/tmp/private.txt'
const terminal = new FakeTerminal([
{ kind: 'line', value: absolutePath },
{ kind: 'line', value: `/rename ${absolutePath}` },
{ kind: 'line', value: '/exit' },
])
const pastedAttachmentPaths = vi.fn(async (value: string) =>
value === absolutePath ? [absolutePath] : null
)
const extractAttachmentPaths = vi.fn(async () => ({
paths: [absolutePath],
text: '[File #1]',
}))
const loadAttachments = vi.fn(async () => [])
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
pastedAttachmentPaths,
extractAttachmentPaths,
loadAttachments,
}).parseAsync(['node', 'sim', 'chat'])
expect(terminal.reads[1].initialValue).toBe(`/attach "${absolutePath}"`)
expect(loadAttachments).toHaveBeenCalledTimes(1)
expect(loadAttachments).toHaveBeenCalledWith([])
expect(extractAttachmentPaths).not.toHaveBeenCalled()
expect(loadAttachments).not.toHaveBeenCalledWith([absolutePath])
expect(mocks.requestRaw).not.toHaveBeenCalled()
})
@@ -1628,8 +1621,8 @@ describe('interactive chat', () => {
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
clipboardImage: async () => attachment,
pastedAttachmentPaths: async () => null,
clipboardAttachment: async () => attachment,
extractAttachmentPaths: async () => null,
}).parseAsync(['node', 'sim', 'chat'])
expect(terminal.reads[1].initialValue).toBe('')
@@ -1738,7 +1731,7 @@ describe('interactive chat', () => {
expect(terminal.preloads).toEqual([])
})
it('leaves the active turn running for a queued path recognized by normal chat input', async () => {
it('steers the active turn with a queued line carrying a file path', async () => {
const pathInput = {
kind: 'line' as const,
value: 'report.txt',
@@ -1747,8 +1740,8 @@ describe('interactive chat', () => {
}
const terminal = new FakeTerminal([pathInput, { kind: 'line', value: '/exit' }])
let requestSignal: AbortSignal | undefined
const pastedAttachmentPaths = vi.fn(async (value: string) =>
value === 'report.txt' ? ['report.txt'] : null
const extractAttachmentPaths = vi.fn(async (value: string) =>
value === 'report.txt' ? { paths: ['report.txt'], text: '[File #1]' } : null
)
mocks.requestRaw.mockImplementationOnce(
async (_path: string, options: { signal: AbortSignal }) => {
@@ -1762,15 +1755,11 @@ describe('interactive chat', () => {
await program(async () => '', vi.fn(), {
isInteractive: () => true,
createTerminal: () => terminal,
pastedAttachmentPaths,
extractAttachmentPaths,
}).parseAsync(['node', 'sim', 'chat', 'original'])
expect(requestSignal?.aborted).toBe(false)
expect(terminal.preloads).toContainEqual({
value: '/attach "report.txt"',
queued: false,
})
expect(mocks.requestRaw).toHaveBeenCalledTimes(1)
expect(requestSignal?.aborted).toBe(true)
expect(terminal.preloads).toEqual([{ value: 'report.txt', queued: true }])
})
it('queues /chats without interrupting the active stream', async () => {
+34 -70
View File
@@ -21,10 +21,10 @@ import { safeOneLine, sanitize } from '../../output/render.js'
import {
type ChatAttachment,
combineChatAttachments,
existingAttachmentPaths,
type ExtractedAttachments,
extractAttachmentPaths,
loadChatAttachments,
parseAttachmentPaths,
readClipboardImage,
readClipboardAttachment,
} from './chat-attachments.js'
import { ChatMarkdownStream } from './chat-markdown.js'
import {
@@ -50,8 +50,8 @@ export interface ChatDependencies {
isInteractive: () => boolean
createTerminal: () => ChatTerminal
loadAttachments: (paths: string[]) => Promise<ChatAttachment[]>
clipboardImage: () => Promise<ChatAttachment | null>
pastedAttachmentPaths: (input: string) => Promise<string[] | null>
clipboardAttachment: () => Promise<ChatAttachment | null>
extractAttachmentPaths: (input: string) => Promise<ExtractedAttachments | null>
formatMarkdown: () => boolean
}
@@ -383,8 +383,8 @@ function explainInteractiveCommands(terminal: ChatTerminal): void {
terminal.status(
[
'Commands:',
' /attach <paths> attach local files to the next turn',
' ctrl+v attach an image from the clipboard (or cmd+v on macOS)',
' ctrl+v attach the clipboard image or file (or cmd+v on macOS)',
' <file path> drop or type a path to attach the file',
' /clear start a new conversation',
' /chats view and switch chats',
' /rename <title> rename the active chat',
@@ -399,12 +399,6 @@ function attachmentStatus(attachments: ChatAttachment[]): string {
return `Attached for the next turn (${attachments.length}/${5}): ${names}`
}
function attachmentCommand(paths: string[]): string | null {
if (paths.some((path) => /[\u0000-\u001f\u007f]/u.test(path))) return null
const quoted = paths.map((path) => `"${path.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`)
return `/attach ${quoted.join(' ')}`
}
async function addPaths(
current: ChatAttachment[],
paths: string[],
@@ -423,18 +417,18 @@ async function addPaths(
}
}
async function addClipboardImage(
async function addClipboardAttachment(
current: ChatAttachment[],
terminal: ChatTerminal,
dependencies: ChatDependencies
): Promise<ChatAttachment[]> {
const image = await dependencies.clipboardImage()
const pasted = await dependencies.clipboardAttachment()
/* Paste feedback is the `[Image #N]` tag in the composer, not a transcript
line: the tag says what was attached and disappears when it is deleted. */
if (!image) return current
if (!pasted) return current
try {
const combined = combineChatAttachments(current, [image])
terminal.noteAttachment()
const combined = combineChatAttachments(current, [pasted])
terminal.noteAttachment(pasted.mediaType.startsWith('image/') ? 'Image' : 'File')
return combined
} catch {
return current
@@ -461,12 +455,12 @@ async function readUserTurn(
continue
}
if (input.kind === 'clipboard') {
attachments = await addClipboardImage(attachments, terminal, dependencies)
attachments = await addClipboardAttachment(attachments, terminal, dependencies)
continue
}
if (input.kind === 'selection') continue
const trimmed = input.value.trim()
let trimmed = input.value.trim()
if (trimmed === '/exit' || trimmed === '/quit') return { kind: 'exit' }
if (trimmed === '/help') {
explainInteractiveCommands(terminal)
@@ -492,42 +486,18 @@ async function readUserTurn(
}
return { kind: 'rename', title, attachments }
}
if (trimmed === '/attach' || trimmed.startsWith('/attach ')) {
const rawPaths = trimmed.slice('/attach'.length).trim()
if (!rawPaths) {
terminal.status('Usage: /attach <path> [more paths]')
continue
}
try {
attachments = await addPaths(
attachments,
parseAttachmentPaths(rawPaths),
terminal,
dependencies
)
} catch (error) {
terminal.status(`Error: ${error instanceof Error ? error.message : String(error)}`)
}
continue
}
if (trimmed) {
const pastedPaths = await dependencies.pastedAttachmentPaths(input.value)
if (pastedPaths) {
// A dragged path is still just user input. Preload an explicit command
// so the next Enter is the user's confirmation before any bytes are read.
const command = attachmentCommand(pastedPaths)
if (!command) {
terminal.status('The detected path cannot be safely preloaded. Use /attach manually.')
let prompt = input.value
if (trimmed && !trimmed.startsWith('/')) {
const extracted = await dependencies.extractAttachmentPaths(input.value)
if (extracted) {
try {
attachments = await addPaths(attachments, extracted.paths, terminal, dependencies)
prompt = extracted.text
trimmed = prompt.trim()
} catch (error) {
terminal.status(`Error: ${error instanceof Error ? error.message : String(error)}`)
continue
}
if (!terminal.preload(command)) {
terminal.status(
'File path detected, but newer composer input took priority. Use /attach to add it.'
)
continue
}
terminal.status('File path detected. Press Enter to attach it, or edit the command.')
continue
}
}
if (trimmed.startsWith('/')) {
@@ -540,13 +510,13 @@ async function readUserTurn(
}
}
if (!trimmed && attachments.length === 0) continue
if (utf8Bytes(input.value) > MAX_CHAT_PROMPT_BYTES) {
if (utf8Bytes(prompt) > MAX_CHAT_PROMPT_BYTES) {
terminal.status('Error: Chat input exceeds the 10 MiB limit.')
continue
}
return {
kind: 'turn',
prompt: input.value,
prompt,
attachments,
queued: input.queued === true,
...(input.display === undefined ? {} : { display: input.display }),
@@ -577,19 +547,13 @@ async function answerQuestions(
return { kind: 'answer', value: answers.join('\n') }
}
async function isChatTurnInput(
input: Extract<ChatTerminalInput, { kind: 'line' }>,
dependencies: Pick<ChatDependencies, 'pastedAttachmentPaths'>
): Promise<boolean> {
function isChatTurnInput(input: Extract<ChatTerminalInput, { kind: 'line' }>): boolean {
const trimmed = input.value.trim()
if (!trimmed) return false
if (
trimmed.startsWith('/') &&
!input.contexts?.some((context) => context.kind === 'skill' || context.kind === 'mcp')
) {
return false
}
return !(await dependencies.pastedAttachmentPaths(input.value))
return (
!trimmed.startsWith('/') ||
input.contexts?.some((context) => context.kind === 'skill' || context.kind === 'mcp') === true
)
}
function logSuggestionLabel(
@@ -1192,7 +1156,7 @@ async function runInteractive(
}
if (input?.kind !== 'line') return
submitChecks = submitChecks.then(async () => {
if (!(await isChatTurnInput(input, dependencies))) return
if (!isChatTurnInput(input)) return
if (!submitRequested) {
submitRequested = true
if (sessionReady && !controller.signal.aborted) controller.abort(reason)
@@ -1493,8 +1457,8 @@ export function chatCommand(overrides: Partial<ChatDependencies> = {}): Command
Boolean(process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY),
createTerminal: () => new ReadlineChatTerminal(),
loadAttachments: loadChatAttachments,
clipboardImage: readClipboardImage,
pastedAttachmentPaths: existingAttachmentPaths,
clipboardAttachment: readClipboardAttachment,
extractAttachmentPaths,
// The fullscreen chat already requires a TTY and uses ANSI throughout. A
// propagated TERM=dumb value must not leave model Markdown visible inside
// an otherwise fully rendered TUI.