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
2 changes: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion docs/chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -1963,7 +1963,13 @@ lists the first two between the places and the tasks.
snoozed). The words and files move to the ghost chat's draft at Home, out of any project
or task it was being started in (ghost chats live outside projects), as the header's ghost
switch does for a chat at Home (`placeDraft(…, ghost)` in `useChatDrafts.ts`). A ghost
chat's composer offers no `/` or `$` menu; the header's switch turns it back.
chat's composer offers no `/` skills and no places, but its `$` menu has one row, the way
out: **`$regular`** (also `$back`, `$keep`, `$normal`, `$exit`, `$unghost`, `$leave`,
`$off` and `$ghost` again, from two letters; a bare `$` shows it too;
`ghostDestinations` in `destinations.ts`). Before the first send it is **Regular chat**,
which moves the words and files to Home's ordinary draft, as the header's switch does; once
the chat has started it is **Keep this chat**, the header's Keep (`keepThread`), and the
words stay in the box. A price (`$40`) or any other word offers nothing, so Enter sends it.
- **A name nothing has yet** (`$tax-returns`, three letters on) ends the menu with
**New project “Tax returns”**, and, in a project or one of its folders, first **New
folder “Tax returns”** in that project (one level of folders). The name is the term as
Expand Down
46 changes: 34 additions & 12 deletions web/src/chat/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { insertMention, mentionAtCaret } from './mentions'
import { attachmentRef, editableRefs, formatSize, refIds, splitRefs } from './refs'
import type { ChipInfo } from './RefChip'
import type { PromptEditorHandle } from './editor/PromptEditor'
import { rankDestinations, stripToken, type Destination } from './destinations'
import { ghostDestinations, rankDestinations, stripToken, type Destination } from './destinations'
import { readNewTask, type NewTaskFields } from './newTask'
import NewTaskBar from './NewTaskBar'
import { folderNames } from '../todos/folders'
Expand All @@ -25,7 +25,7 @@ import { TI, ProviderLogo, useDismiss } from './ui'
import {
IconArrowUp, IconPlayerStopFilled, IconPlus, IconPaperclip, IconPhoto, IconMicrophone, IconWaveSine,
IconSparkles, IconX, IconCheck, IconLoader2, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled,
IconHome, IconChecklist, IconTable, IconFolder, IconFolderPlus, IconGhost2, IconPinned, IconZzz, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus,
IconHome, IconChecklist, IconTable, IconFolder, IconFolderPlus, IconGhost2, IconGhostOff, IconPinned, IconZzz, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus,
} from './icons'
import { formatContextTokens } from './context'
import type { ChatCommand } from '../studio'
Expand Down Expand Up @@ -128,6 +128,12 @@ export interface ComposerProps {
/** The draft on screen: a task line is that draft's, so another draft is a message again. */
draftKey?: string
}
/**
* A ghost chat. Its `/` and `$` menus are off (`allowCommands` false) but for one
* row, the way out: `$regular`, `$back`, `$keep`. Not started yet, it goes through
* `destinations.onPick` (the words move to Home's regular draft); started, `onKeep`.
*/
ghost?: { started: boolean; onKeep?: () => void }
}

const coarse = () => window.matchMedia?.('(pointer: coarse)').matches
Expand Down Expand Up @@ -157,15 +163,17 @@ type MenuItem = { kind: 'dest'; d: Destination } | { kind: 'cmd'; c: ChatCommand
const itemKey = (it: MenuItem) => (it.kind === 'dest' ? it.d.key : it.c.cmd)
const NO_PROVIDERS: ProviderRow[] = []
const NO_CATALOGS: Record<string, ModelRow[]> = {}
const QUICK = new Set(['new-task', 'ghost', 'pin'])
const QUICK = new Set(['new-task', 'ghost', 'leave-ghost', 'pin'])
/** Picks that leave the draft where it is, so a file still uploading doesn't hold them. */
const STAYS = new Set(['new-task', 'model', 'pin', 'snooze'])
const stays = (d: Destination) => STAYS.has(d.kind) || (d.kind === 'leave-ghost' && d.started)
const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (QUICK.has(it.d.kind) ? 'Quick actions' : it.d.kind === 'snooze' ? 'Send it, back later' : it.d.kind === 'model' ? 'Start on a model' : it.d.kind === 'new-folder' ? 'Make a folder' : it.d.kind === 'task' ? 'Start it for a task' : 'Start it in')
: it.c.kind === 'agent' ? 'Your agent skills' : 'Totem skills')

function destDesc(d: Destination, sheetName: string, here?: Project, forTask = false) {
if (d.kind === 'new-task') return here ? `Type it here, filed in ${here.name}, then chat about it` : 'Type it here, then start a chat for it'
if (d.kind === 'ghost') return here || forTask ? 'Not kept: moves to Home, gone at midnight' : 'Not kept: gone at midnight, or as soon as you settle it'
if (d.kind === 'leave-ghost') return d.started ? 'Kept after midnight, like any other chat' : 'Kept: an ordinary chat at Home'
if (d.kind === 'new-folder') return d.parent ? `New folder in ${d.parent.name}, then start the chat in it` : 'New project, then start the chat in it'
if (d.kind === 'model') return d.note ? `${d.provider.name} · ${d.note}` : d.provider.name
if (d.kind === 'pin') return 'Pinned to the top of your chats once it starts'
Expand All @@ -181,6 +189,7 @@ function DestIcon({ d }: { d: Destination }) {
if (d.kind === 'home') return <TI icon={IconHome} size={16} />
if (d.kind === 'new-task') return <TI icon={IconSquarePlus} size={16} />
if (d.kind === 'ghost') return <TI icon={IconGhost2} size={16} />
if (d.kind === 'leave-ghost') return <TI icon={IconGhostOff} size={16} />
if (d.kind === 'new-folder') return <TI icon={IconFolderPlus} size={16} />
if (d.kind === 'model') return <ProviderLogo driver={d.provider.driver} name={d.provider.name} size={16} />
if (d.kind === 'pin') return <TI icon={IconPinned} size={16} />
Expand Down Expand Up @@ -273,7 +282,7 @@ const PlainBox = forwardRef<HTMLTextAreaElement, {
})

const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(props, ref) {
const { value, onChange, onAttachmentsChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, leftSlot, compactSend, answering, above, destinations } = props
const { value, onChange, onAttachmentsChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, leftSlot, compactSend, answering, above, destinations, ghost } = props
const ed = useRef<PromptEditorHandle>(null)
const fileInput = useRef<HTMLInputElement>(null)
const photoInput = useRef<HTMLInputElement>(null)
Expand Down Expand Up @@ -553,21 +562,26 @@ const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(pro
// A message that is only a Totem command still runs that skill on its own.
const catalog = useSyncExternalStore(subscribeChatCommands, getChatCommands, getChatCommands)
const known = useMentionSet()
const token = allowCommands && !dictation && !inTask ? mentionAtCaret(value, caret) : null
// A ghost chat reads only `$`, for its way out (no skills, no places).
const ghostOnly = !allowCommands && !!ghost
const rawToken = (allowCommands || ghostOnly) && !dictation && !inTask ? mentionAtCaret(value, caret) : null
const token = rawToken && (!ghostOnly || rawToken.prefix === '$') ? rawToken : null
const query = token && token.start !== dismissed ? token : null
// Only the token in an otherwise empty box can take a fill-mode skill's prefix.
const alone = !!query && query.start === 0 && !value.slice(query.end).trim()
const matches: ChatCommand[] = query ? rankCommands(catalog, query.prefix, query.term, alone) : []
const matches: ChatCommand[] = query && !ghostOnly ? rankCommands(catalog, query.prefix, query.term, alone) : []
// `$` in a chat not started yet: where it goes and which task it is for, before the `$` skills.
const dollar = !!query && query.prefix === '$' && !!destinations
const dollar = !!query && query.prefix === '$' && !!destinations && !ghostOnly
const work = useSyncExternalStore(dollar ? subscribeWork : noSubscribe, getWork, getWork)
const providers = useChat((s) => s.providers) || NO_PROVIDERS
const catalogs = useChat((s) => s.models) || NO_CATALOGS
const wantModels = dollar && !!destinations?.onModel && query!.term.length >= 2
// Every account's models, so `$opus` finds a model on any of them (the picker loads them the same way).
useEffect(() => { if (wantModels) for (const p of providers) ensureModels(p.id) }, [wantModels, providers])
const accounts = useMemo(() => providers.map((provider) => ({ provider, models: catalogs[provider.id] || [] })), [providers, catalogs])
const places = dollar && destinations
const places = ghostOnly && query?.prefix === '$'
? ghostDestinations(query.term, ghost!.started)
: dollar && destinations
? rankDestinations({
projects, tasks: work.tasks, projectId: destinations.projectId, taskId: destinations.taskId,
models: destinations.onModel ? accounts : [], startOptions: !!destinations.onStartOption, pinned: destinations.pinned,
Expand Down Expand Up @@ -599,9 +613,17 @@ const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(pro

function chooseItem(it: MenuItem) {
if (it.kind === 'cmd') { chooseCommand(it.c); return }
if (!query || !destinations) return
// Only a move waits for uploads: a model, pin or snooze leaves the files where they are.
if (placeHeld && !STAYS.has(it.d.kind)) return
if (!query) return
// Only a move waits for uploads: a model, pin, snooze or Keep leaves the files where they are.
if (placeHeld && !stays(it.d)) return
if (it.d.kind === 'leave-ghost' && it.d.started) {
const { value: next, caret: pos } = stripToken(value, query.start, query.end)
setDismissed(null)
placeCaret(next, pos)
ghost?.onKeep?.()
return
}
if (!destinations) return
const { value: next, caret: pos } = stripToken(value, query.start, query.end)
setDismissed(null)
if (it.d.kind === 'new-task') { placeCaret(next, pos); startTask(); return }
Expand Down Expand Up @@ -757,7 +779,7 @@ const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(pro
<span className="vc-cmd-icon"><DestIcon d={it.d} /></span>
<span className="vc-cmd-text">
<span className="vc-cmd-place">{it.d.kind === 'new-folder' ? `New ${it.d.parent ? 'folder' : 'project'} “${it.d.name}”` : it.d.kind === 'snooze' ? `Snooze · ${it.d.name}` : it.d.name}</span>
<span className="vc-cmd-desc">{(!STAYS.has(it.d.kind) && placeHeld) || destDesc(it.d, work.sheetName, here, !!destinations?.taskId)}</span>
<span className="vc-cmd-desc">{(!stays(it.d) && placeHeld) || destDesc(it.d, work.sheetName, here, !!destinations?.taskId)}</span>
</span>
</>
) : (
Expand Down
36 changes: 35 additions & 1 deletion web/src/chat/composerDestinations.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,16 @@ const { default: Composer } = await import('./Composer')

afterEach(cleanup)

function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {}, onModel, onStartOption, valueSpy }: {
function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {}, onModel, onStartOption, valueSpy, ghost }: {
onPick: (d: Destination, text: string) => void; destinations?: boolean
onNewTask?: (fields: NewTaskFields) => Promise<boolean>; projectId?: string | null; onSend?: () => void
onModel?: (d: any) => void; onStartOption?: (d: any) => void; valueSpy?: (v: string) => void
ghost?: { started: boolean; onKeep?: () => void }
}) {
const [value, setValue] = useState('')
return (
<Composer value={value} onChange={(v) => { valueSpy?.(v); setValue(v) }} onSend={onSend} onStop={() => {}} busy={false}
allowCommands={!ghost} ghost={ghost}
destinations={destinations ? { projectId, taskId: null, onPick: (d, text) => onPick(d, text), onNewTask, onModel, onStartOption } : undefined} />
)
}
Expand Down Expand Up @@ -109,6 +111,38 @@ describe('composer $ destinations', () => {
expect(onPick.mock.calls[0][1]).toBe('just between us')
})

it('in a ghost chat not started, $regular is the only row and moves the words to a regular chat', async () => {
const onPick = vi.fn()
render(<Harness onPick={onPick} ghost={{ started: false }} />)
const box = await type('on second thought $regu')
const options = screen.getAllByRole('option').map((o) => o.textContent)
expect(options).toHaveLength(1)
expect(options[0]).toContain('Regular chat')
fireEvent.keyDown(box, { key: 'Enter' })
expect(onPick.mock.calls[0][0]).toMatchObject({ kind: 'leave-ghost', started: false })
expect(onPick.mock.calls[0][1]).toBe('on second thought')
})

it('in a started ghost chat, $back keeps it and leaves the words in the box', async () => {
const onPick = vi.fn()
const onKeep = vi.fn()
const valueSpy = vi.fn()
render(<Harness onPick={onPick} destinations={false} ghost={{ started: true, onKeep }} valueSpy={valueSpy} />)
const box = await type('one more thing $back')
expect(screen.getAllByRole('option')[0].textContent).toContain('Keep this chat')
fireEvent.keyDown(box, { key: 'Enter' })
expect(onKeep).toHaveBeenCalledTimes(1)
expect(onPick).not.toHaveBeenCalled()
expect(valueSpy).toHaveBeenLastCalledWith('one more thing')
})

it('a ghost chat still offers no places, tasks or skills', async () => {
const onPick = vi.fn()
render(<Harness onPick={onPick} ghost={{ started: false }} />)
await type('$harb')
expect(screen.queryAllByRole('option')).toHaveLength(0)
})

it('offers a new folder in the project, and a new project, for a name nothing has, with his capitals', async () => {
const onPick = vi.fn()
render(<Harness onPick={onPick} projectId="harbor" />)
Expand Down
22 changes: 21 additions & 1 deletion web/src/chat/destinations.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { matchScore, nameFromTerm, placeAfter, rankDestinations, slug, stripToken } from './destinations'
import { ghostDestinations, matchScore, nameFromTerm, placeAfter, rankDestinations, slug, stripToken } from './destinations'
import type { Project } from './types'
import type { WorkTask } from '../work/groups'

Expand Down Expand Up @@ -215,3 +215,23 @@ describe('$opus, $pin and $snooze', () => {
for (const term of ['opus', 'pin', 'snooze-tom']) expect(placeAfter(rankDestinations(ctx, term)[0], now, () => 'wp')).toEqual(now)
})
})

describe('ghostDestinations', () => {
it('offers only the way out, for a bare $ or a word that asks for it', () => {
expect(ghostDestinations('', false)).toEqual([{ kind: 'leave-ghost', key: 'leave-ghost', name: 'Regular chat', started: false }])
for (const t of ['re', 'regular', 'back', 'ba', 'keep', 'normal', 'exit', 'unghost', 'leave', 'gh', 'off']) {
expect(ghostDestinations(t, false).map((d) => d.kind)).toEqual(['leave-ghost'])
}
expect(ghostDestinations('back', true)[0]).toMatchObject({ name: 'Keep this chat', started: true })
})

it('offers nothing for a price or any other word, so Enter sends it', () => {
expect(ghostDestinations('40', false)).toEqual([])
expect(ghostDestinations('r', false)).toEqual([])
expect(ghostDestinations('harbor', false)).toEqual([])
})

it('leaves to Home, out of any task', () => {
expect(placeAfter(ghostDestinations('back', false)[0], { taskId: 't1', projectId: 'wp' }, () => 'wp')).toEqual({ taskId: null, projectId: null })
})
})
24 changes: 21 additions & 3 deletions web/src/chat/destinations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
// a ghost chat (not kept: gone at midnight), and a name no place has yet
// (`$tax-returns`) offers a new folder or project by that name, `$opus` (any model
// or account name) picks the chat's model, `$pin` pins it from the start, and
// `$snooze` sends it now and keeps it out of the way until a time. Pure, so the
// `$snooze` sends it now and keeps it out of the way until a time. In a ghost chat
// `$` offers one thing, the way out: `$regular` (or `$back`, `$keep`) makes it a
// chat that is kept, as the header's switch or Keep does. Pure, so the
// composer's menu and its tests read the same rules.
import type { ModelRow, Project, ProviderRow } from './types'
import type { WorkTask } from '../work/groups'
Expand All @@ -18,6 +20,8 @@ export type Destination =
| { kind: 'task'; key: string; name: string; task: WorkTask }
| { kind: 'new-task'; key: 'new-task'; name: 'New task' }
| { kind: 'ghost'; key: 'ghost'; name: 'Ghost chat' }
/** Out of a ghost chat: a kept chat at Home (not started yet), or Keep (started). */
| { kind: 'leave-ghost'; key: 'leave-ghost'; name: string; started: boolean }
/** A folder (in `parent`) or a top-level project, made by that name, then the chat starts in it. */
| { kind: 'new-folder'; key: string; name: string; parent?: Project }
/** A model to start on (no `modelId`: the account's own default). */
Expand All @@ -36,6 +40,20 @@ const GHOST_WORDS: Array<[string, number]> = [['ghost', 2], ['temporary', 4], ['
export const wantsGhost = (term: string) => GHOST_WORDS.some(([w, min]) => term.length >= min && w.startsWith(term))
const GHOST: Destination = { kind: 'ghost', key: 'ghost', name: 'Ghost chat' }

/** The way out of a ghost chat: `$regular`, `$back`, `$keep`, `$normal`, `$exit`, `$unghost`, `$leave`, `$ghost` again, from two letters. */
const LEAVE_GHOST_WORDS = ['regular', 'back', 'keep', 'normal', 'exit', 'unghost', 'leave', 'ghost', 'off']
export const wantsLeaveGhost = (term: string) => term.length >= 2 && LEAVE_GHOST_WORDS.some((w) => w.startsWith(term))

/**
* A ghost chat's `$` menu: only the way out, for a bare `$` or a term that asks for it.
* `started`: the chat has messages, so it is kept where it is (Keep) rather than moved.
*/
export function ghostDestinations(term: string, started: boolean): Destination[] {
const t = term.toLowerCase()
if (t && !wantsLeaveGhost(t)) return []
return [{ kind: 'leave-ghost', key: 'leave-ghost', name: started ? 'Keep this chat' : 'Regular chat', started }]
}

/** `$pin` from `$pi`. */
export const wantsPin = (term: string) => term.length >= 2 && 'pin'.startsWith(term)
const PIN: Destination = { kind: 'pin', key: 'pin', name: 'Pin it' }
Expand Down Expand Up @@ -223,8 +241,8 @@ export function placeAfter(d: Destination, now: { taskId: string | null; project
// "New task" and "New folder" move nothing until the task or folder exists (made first);
// a model, a pin or a snooze changes how it starts, not where.
if (d.kind === 'new-task' || d.kind === 'new-folder' || d.kind === 'model' || d.kind === 'pin' || d.kind === 'snooze') return now
// A ghost chat lives at Home, outside any project or task.
if (d.kind === 'ghost') return { taskId: null, projectId: null }
// A ghost chat lives at Home, outside any project or task, and leaving one stays there.
if (d.kind === 'ghost' || d.kind === 'leave-ghost') return { taskId: null, projectId: null }
if (d.kind === 'home') return { taskId: now.taskId, projectId: null }
if (d.kind === 'project') return { taskId: now.taskId, projectId: d.project.id }
return { taskId: d.task.ref, projectId: taskHome(d.task.ref) ?? now.projectId }
Expand Down
1 change: 1 addition & 0 deletions web/src/chat/icons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export { default as IconEdit } from '@tabler/icons-react/dist/esm/icons/IconEdit
export { default as IconLayoutSidebar } from '@tabler/icons-react/dist/esm/icons/IconLayoutSidebar.mjs'
export { default as IconPinned } from '@tabler/icons-react/dist/esm/icons/IconPinned.mjs'
export { default as IconGhost2 } from '@tabler/icons-react/dist/esm/icons/IconGhost2.mjs'
export { default as IconGhostOff } from '@tabler/icons-react/dist/esm/icons/IconGhostOff.mjs'
export { default as IconPuzzle } from '@tabler/icons-react/dist/esm/icons/IconPuzzle.mjs'
export { default as IconMessageCircleQuestion } from '@tabler/icons-react/dist/esm/icons/IconMessageCircleQuestion.mjs'
export { default as IconBolt } from '@tabler/icons-react/dist/esm/icons/IconBolt.mjs'
Expand Down
Loading
Loading