Open History to see the last commit
1import { useState } from 'react'
2import { Box, Static, Text, render, useApp, useInput } from 'ink'
3import { useSelector } from '@tanstack/react-store'
4import type {
5 SessionView,
6 ViewMessage,
7 ViewPart,
8} from '@tanstack/ai-harness/view'
9
10function Part({ part }: { part: ViewPart }) {
11 switch (part.type) {
12 case 'text':
13 return <Text>{part.text}</Text>
14 case 'reasoning':
15 return <Text dimColor>{part.text}</Text>
16 case 'tool-call':
17 return (
18 <Text color={part.status === 'failed' ? 'red' : 'yellow'}>
19 {`* ${part.name} (${part.status})`}
20 </Text>
21 )
22 case 'agent':
23 return (
24 <Box flexDirection="column" marginLeft={2}>
25 <Text color="cyan">{`${part.name} (${part.status})`}</Text>
26 {part.parts.map((child, index) => (
27 <Part key={index} part={child} />
28 ))}
29 </Box>
30 )
31 case 'media':
32 return <Text color="magenta">{`[${part.kind}: ${part.name}]`}</Text>
33 }
34}
35
36function Message({ message }: { message: ViewMessage }) {
37 if (message.role === 'user') {
38 return <Text color="green">{`> ${message.text}`}</Text>
39 }
40 if (message.role === 'notice') {
41 return (
42 <Text color={message.kind === 'error' ? 'red' : 'gray'}>
43 {message.text}
44 </Text>
45 )
46 }
47 return (
48 <Box flexDirection="column">
49 {message.parts.map((part, index) => (
50 <Part key={index} part={part} />
51 ))}
52 </Box>
53 )
54}
55
56/** The typed answer: JSON (a number, a boolean) unless the question wants text. */
57function answerOf(text: string, schema: unknown): unknown {
58 const wantsText =
59 typeof schema !== 'object' ||
60 schema === null ||
61 Reflect.get(schema, 'type') === 'string'
62 if (wantsText) return text
63 try {
64 return JSON.parse(text)
65 } catch {
66 return text
67 }
68}
69
70/** The whole screen: the messages, then one line for what waits for you. */
71function Screen({ view }: { view: SessionView }) {
72 const { exit } = useApp()
73 const state = useSelector(view.store)
74 const [line, setLine] = useState('')
75 // The turn goes on when every approval and interrupt has an answer, so the
76 // screen asks them one by one.
77 const [answered, setAnswered] = useState<ReadonlyArray<string>>([])
78 const approval = state.approvals.find(({ id }) => !answered.includes(id))
79 const interrupt = state.interrupts.find(({ id }) => !answered.includes(id))
80 const [question] = state.questions
81
82 useInput((input, key) => {
83 if (key.escape) {
84 void view.cancel()
85 return
86 }
87 // An approval takes one key: y or n.
88 if (approval) {
89 if (input !== 'y' && input !== 'n') return
90 if (input === 'y') approval.approve()
91 else approval.reject()
92 setAnswered((ids) => [...ids, approval.id])
93 return
94 }
95 if (key.return) {
96 const text = line.trim()
97 setLine('')
98 if (text === '/exit') exit()
99 else if (interrupt) {
100 interrupt.resolve(answerOf(text, interrupt.responseSchema))
101 setAnswered((ids) => [...ids, interrupt.id])
102 } else if (question) {
103 void question
104 .answer(answerOf(text, question.schema))
105 .then((receipt) => {
106 if (receipt.status === 'rejected') {
107 view.notice({
108 text: `Answer again: ${receipt.reason ?? 'not accepted'}`,
109 })
110 }
111 })
112 }
113 // A `/command` runs the command. Text while a turn runs steers it.
114 else void view.send(text)
115 return
116 }
117 if (key.backspace || key.delete) {
118 setLine((value) => value.slice(0, -1))
119 return
120 }
121 // A paste can hold line breaks. The line stays one line.
122 if (!key.ctrl && !key.meta) {
123 setLine((value) => value + input.replace(/[\r\n]+/g, ' '))
124 }
125 })
126
127 // The turns before the last message you sent do not change, so Ink prints
128 // them once. Only the running turn redraws.
129 let lastSent = 0
130 state.messages.forEach((message, index) => {
131 if (message.role === 'user') lastSent = index
132 })
133 const done = state.messages.slice(0, lastSent)
134 const live = state.messages.slice(lastSent)
135
136 const typed = question?.secret ? '*'.repeat(line.length) : line
137 const asking = interrupt
138 ? (interrupt.message ?? interrupt.reason)
139 : question?.message
140 const prompt = asking ? `? ${asking} ` : '> '
141 return (
142 <Box flexDirection="column">
143 <Static items={done}>
144 {(message) => <Message key={message.id} message={message} />}
145 </Static>
146 {live.map((message) => (
147 <Message key={message.id} message={message} />
148 ))}
149 {state.signIns.map((signIn) => (
150 <Text key={signIn.connector} color="cyan">
151 {`Sign in to ${signIn.connector}: ${signIn.url ?? ''} ${signIn.userCode ?? ''}`}
152 </Text>
153 ))}
154 {approval ? (
155 <Text color="yellow">
156 {`Run ${approval.tool} ${JSON.stringify(approval.args)}? (y/n)`}
157 </Text>
158 ) : (
159 <Box flexDirection="column">
160 {question?.url ? (
161 <Text color="cyan">{`Open ${question.url}`}</Text>
162 ) : null}
163 <Text>{`${prompt}${typed}`}</Text>
164 </Box>
165 )}
166 <Text dimColor>
167 {`${state.status}. Enter sends, Esc cancels, /exit quits.`}
168 </Text>
169 </Box>
170 )
171}
172
173/** The ids of the child agent parts in `parts`, at any depth. */
174function agentIds(parts: ReadonlyArray<ViewPart>): Array<string> {
175 return parts.flatMap((part) =>
176 part.type === 'agent' ? [part.id, ...agentIds(part.parts)] : [],
177 )
178}
179
180/**
181 * Fill the saved child agents of a reopened thread. Ink prints the old turns
182 * once, so they load before the first render. A loaded child can have saved
183 * children of its own, so it loads again until no new id shows up.
184 */
185async function loadSavedAgents(view: SessionView) {
186 const loaded = new Set<string>()
187 for (;;) {
188 const ids = view.store
189 .get()
190 .messages.flatMap((message) =>
191 message.role === 'assistant' ? agentIds(message.parts) : [],
192 )
193 .filter((id) => !loaded.has(id))
194 if (ids.length === 0) return
195 for (const id of ids) loaded.add(id)
196 await Promise.all(ids.map((id) => view.loadAgent({ id })))
197 }
198}
199
200/** The `ui` of runCli: show the screen until the user quits. */
201export async function runTui(view: SessionView) {
202 await loadSavedAgents(view)
203 await render(<Screen view={view} />).waitUntilExit()
204}