Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cowork): edit, re-ask and delete a question from the transcript

Akarshan Biswas5115899d3531
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 236514e34..0fa69674d 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -62,6 +62,11 @@ export type MessageItemProps = {
onContinue?: (messageId: string) => void
onEdit?: (messageId: string, newText: string) => void
onDelete?: (messageId: string) => void
+ /** Ask this question again, unchanged, dropping whatever it produced. Only
+ * offered where re-running from partway up the transcript is meaningful --
+ * the agent surfaces, where a turn is a chain of tool calls rather than a
+ * single reply. */
+ onRetry?: (messageId: string, text: string) => void
versionInfo?: { index: number; count: number }
onSwitchVersion?: (messageId: string, dir: -1 | 1) => void
// Cowork only: the session's background subagent runs. Omitted in regular
@@ -88,6 +93,7 @@ export const MessageItem = memo(
onContinue,
onEdit,
onDelete,
+ onRetry,
versionInfo,
onSwitchVersion,
}: MessageItemProps) => {
@@ -644,6 +650,19 @@ export const MessageItem = memo(
/>
)}
+ {onRetry &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onRetry(message.id, getFullTextContent())}
+ title={t('chat:actions.askAgain')}
+ >
+ <IconRefresh size={16} className="text-muted-foreground" />
+ </Button>
+ )}
+
{onDelete &&
status !== CHAT_STATUS.STREAMING &&
status !== CHAT_STATUS.SUBMITTED && (
diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsx
index 3915e8a0e..8bb5d18fe 100644
--- a/web-app/src/containers/__tests__/MessageItem.test.tsx
+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx
@@ -292,6 +292,48 @@ describe('MessageItem', () => {
expect(onDelete).toHaveBeenCalledWith('msg-1')
})
+ /// One click to ask the same question again, from partway up the transcript
+ /// -- an agent turn is a chain of tool calls, so "regenerate" only ever
+ /// applied to the last one.
+ it('fires onRetry with the question text', () => {
+ const onRetry = vi.fn()
+ render(
+ <MessageItem
+ message={
+ makeMsg({
+ role: 'user',
+ parts: [{ type: 'text', text: 'ask me again' }],
+ }) as any
+ }
+ isFirstMessage
+ isLastMessage
+ status={'ready' as any}
+ onRetry={onRetry}
+ />
+ )
+ fireEvent.click(screen.getByTitle('chat:actions.askAgain'))
+ expect(onRetry).toHaveBeenCalledWith(
+ 'msg-1',
+ expect.stringContaining('ask me again')
+ )
+ })
+
+ /// Offered only where a caller opts in: an ordinary chat has `onRegenerate`
+ /// on the answer and no use for a second way to re-ask.
+ it('offers no retry without a handler', () => {
+ render(
+ <MessageItem
+ message={
+ makeMsg({ role: 'user', parts: [{ type: 'text', text: 'x' }] }) as any
+ }
+ isFirstMessage
+ isLastMessage
+ status={'ready' as any}
+ />
+ )
+ expect(screen.queryByTitle('chat:actions.askAgain')).not.toBeInTheDocument()
+ })
+
it('hides actions when hideActions is set', () => {
render(
<MessageItem
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
index 66393cc50..35b94200d 100644
--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
@@ -83,6 +83,59 @@ describe('useCoworkSessions', () => {
expect(s.messages.map((m) => m.id)).toEqual(['m1'])
})
+ /// Editing or deleting a question partway up the transcript cuts both lists
+ /// at that question. The wire history has messages the transcript has no row
+ /// for, so the cut is counted in questions, not in indices.
+ it('drops a question and everything it produced', () => {
+ const id = useCoworkSessions.getState().createSession()
+ const turns: CoworkTurn[] = [
+ { role: 'user', content: 'first' },
+ { role: 'assistant', content: 'answer one' },
+ { role: 'user', content: 'second' },
+ { role: 'tool', content: '', name: 'read', status: 'done' },
+ { role: 'assistant', content: 'answer two' },
+ ]
+ const msgs = [
+ { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'first' }] },
+ { id: 'm2', role: 'assistant', parts: [] },
+ {
+ id: 'ping-2',
+ role: 'user',
+ parts: [{ type: 'text', text: '<SYSTEM>\nalpha done\n</SYSTEM>' }],
+ },
+ { id: 'm3', role: 'user', parts: [{ type: 'text', text: 'second' }] },
+ { id: 'm4', role: 'assistant', parts: [] },
+ ] as never
+ useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
+ useCoworkSessions.getState().dropFromTurn(id, 2)
+
+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.turns.map((t) => t.content)).toEqual(['first', 'answer one'])
+ // The ping belongs to the first question's run, so it survives with it.
+ expect(s.messages.map((m) => m.id)).toEqual(['m1', 'm2', 'ping-2'])
+ })
+
+ /// The answers to a question cannot outlive it, so an assistant or tool turn
+ /// is not a place the transcript can be cut.
+ it('refuses to cut anywhere but a question', () => {
+ const id = useCoworkSessions.getState().createSession()
+ const turns: CoworkTurn[] = [
+ { role: 'user', content: 'first' },
+ { role: 'assistant', content: 'answer' },
+ ]
+ const msgs = [
+ { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'first' }] },
+ { id: 'm2', role: 'assistant', parts: [] },
+ ] as never
+ useCoworkSessions.getState().commitTurns(id, turns, msgs, [])
+ useCoworkSessions.getState().dropFromTurn(id, 1)
+ useCoworkSessions.getState().dropFromTurn(id, 9)
+
+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.turns).toHaveLength(2)
+ expect(s.messages).toHaveLength(2)
+ })
+
// Rewinding a session that has never had a turn would otherwise empty it.
it('leaves a session with no user turn alone', () => {
const id = useCoworkSessions.getState().createSession()
diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.ts
index 2af358956..9515515db 100644
--- a/web-app/src/hooks/useCoworkSessions.ts
+++ b/web-app/src/hooks/useCoworkSessions.ts
@@ -94,6 +94,11 @@ type CoworkSessionsState = {
* be taken again. Both lists are rewound together or the transcript and the
* history the model sees would disagree. */
rewindToLastUser: (id: string) => void
+ /** Drop the question at `turnIndex` and everything after it -- the backing
+ * operation for editing, retrying or deleting a message partway up the
+ * transcript. A no-op unless that turn is a question: the answers to a
+ * question cannot outlive it, so there is nowhere else to cut. */
+ dropFromTurn: (id: string, turnIndex: number) => void
clearSession: (id: string) => void
/** Drop sessions that never got a message, except the current one and any in
* `keepIds` — callers pass sessions with a run in flight, whose first turns
@@ -103,6 +108,35 @@ type CoworkSessionsState = {
const now = () => Date.now()
+type RoleLike = { role: string; parts?: unknown }
+
+/**
+ * A question the user actually asked.
+ *
+ * A `<SYSTEM>` ping is a user *message* but never a user *turn*: the transcript
+ * has no row for it, so counting it would cut the two lists at different points
+ * and leave a session resuming from a note about a subagent.
+ */
+const isQuestion = (m: RoleLike) => m.role === 'user' && !isPingOnly(m)
+
+/** Index of the `ordinal`-th (0-based) question, or -1. */
+function questionIndex(items: RoleLike[], ordinal: number): number {
+ let seen = 0
+ for (let i = 0; i < items.length; i++) {
+ if (!isQuestion(items[i])) continue
+ if (seen === ordinal) return i
+ seen += 1
+ }
+ return -1
+}
+
+function lastQuestionIndex(items: RoleLike[]): number {
+ for (let i = items.length - 1; i >= 0; i--) {
+ if (isQuestion(items[i])) return i
+ }
+ return -1
+}
+
export const useCoworkSessions = create<CoworkSessionsState>()(
persist(
(set, get) => ({
@@ -212,23 +246,12 @@ export const useCoworkSessions = create<CoworkSessionsState>()(
set((s) => ({
sessions: s.sessions.map((x) => {
if (x.id !== id) return x
- // A `<SYSTEM>` ping is a user *message* but never a user *turn*:
- // the transcript has no row for it, so counting it here would cut
- // the two histories at different points and resume the run from a
- // note about a subagent instead of from the question.
- const lastIndexOfUser = (
- roles: { role: string; parts?: unknown }[]
- ) => {
- for (let i = roles.length - 1; i >= 0; i--) {
- if (roles[i].role === 'user' && !isPingOnly(roles[i])) return i
- }
- return -1
- }
- const lastTurn = lastIndexOfUser(x.turns)
- const lastMessage = lastIndexOfUser(x.messages)
+ const lastTurn = lastQuestionIndex(x.turns)
+ const lastMessage = lastQuestionIndex(x.messages)
if (lastTurn < 0 || lastMessage < 0) return x
return {
...x,
+ // The question survives; the run it produced does not.
turns: x.turns.slice(0, lastTurn + 1),
messages: x.messages.slice(0, lastMessage + 1),
updated: now(),
@@ -236,6 +259,31 @@ export const useCoworkSessions = create<CoworkSessionsState>()(
}),
})),
+ dropFromTurn: (id, turnIndex) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => {
+ if (x.id !== id) return x
+ if (x.turns[turnIndex]?.role !== 'user') return x
+ // The wire history holds messages the transcript has no row for
+ // (and vice versa), so the cut is made at the same *question*,
+ // counted, rather than at the same index.
+ const ordinal = x.turns
+ .slice(0, turnIndex)
+ .filter((t) => t.role === 'user').length
+ const cut = questionIndex(x.messages, ordinal)
+ // Out of step (a session saved before the two were kept aligned):
+ // truncating the transcript alone would leave the model answering
+ // questions the user can no longer see.
+ if (cut < 0) return x
+ return {
+ ...x,
+ turns: x.turns.slice(0, turnIndex),
+ messages: x.messages.slice(0, cut),
+ updated: now(),
+ }
+ }),
+ })),
+
clearSession: (id) =>
set((s) => ({
sessions: s.sessions.map((x) =>
diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.json
index 548d43d74..8c6693ded 100644
--- a/web-app/src/locales/en/chat.json
+++ b/web-app/src/locales/en/chat.json
@@ -15,6 +15,7 @@
},
"actions": {
"regenerate": "Regenerate response",
+ "askAgain": "Ask again",
"continue": "Continue generating",
"remember": "Remember this",
"rememberSaved": "Saved to memory as \"{{name}}\"",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index a2353762d..db3ad4781 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -855,6 +855,71 @@ function CoworkPage() {
void runRequestRef.current(null)
}, [running, session?.id])
+ /**
+ * The transcript turn a rendered user message came from.
+ *
+ * Counted rather than parsed out of the message id: the ids are an internal
+ * detail of `coworkTurnsToUIMessages`, and the two lists agree on the order
+ * of the questions whatever those ids look like.
+ */
+ const questionTurnIndex = useCallback(
+ (messageId: string): number => {
+ const ordinal = uiMessages
+ .filter((m) => m.role === 'user')
+ .findIndex((m) => m.id === messageId)
+ if (ordinal < 0) return -1
+ let seen = 0
+ for (let i = 0; i < displayedTurns.length; i++) {
+ if (displayedTurns[i].role !== 'user') continue
+ if (seen === ordinal) return i
+ seen += 1
+ }
+ return -1
+ },
+ [uiMessages, displayedTurns]
+ )
+
+ /**
+ * Edit a question and ask it again.
+ *
+ * The old question and everything it produced are dropped first: an agent
+ * turn is a chain of tool calls against a workspace, so keeping the answers
+ * to a question that was never asked would leave the model reading work it
+ * cannot account for. Same reasoning as `handleRegenerate`, one message
+ * further up.
+ *
+ * The files it touched are *not* rolled back -- there is no checkpoint on this
+ * surface -- so this re-asks, it does not undo.
+ */
+ const handleEditQuestion = useCallback(
+ (messageId: string, newText: string) => {
+ if (running || !session?.id || !newText.trim()) return
+ const index = questionTurnIndex(messageId)
+ if (index < 0) return
+ useCoworkSessions.getState().dropFromTurn(session.id, index)
+ void runRequestRef.current(newText)
+ },
+ [running, session?.id, questionTurnIndex]
+ )
+
+ /** Ask a question again unchanged, from a point partway up the transcript. */
+ const handleRetryQuestion = useCallback(
+ (messageId: string, text: string) => {
+ handleEditQuestion(messageId, text)
+ },
+ [handleEditQuestion]
+ )
+
+ const handleDeleteQuestion = useCallback(
+ (messageId: string) => {
+ if (running || !session?.id) return
+ const index = questionTurnIndex(messageId)
+ if (index < 0) return
+ useCoworkSessions.getState().dropFromTurn(session.id, index)
+ },
+ [running, session?.id, questionTurnIndex]
+ )
+
const abortRef = useRef<AbortController | null>(null)
const askResolvers = useRef(
new Map<string, (answers: AskAnswer[] | null) => void>()
@@ -927,6 +992,30 @@ function CoworkPage() {
isLastMessage={i === uiMessages.length - 1}
status={viewingRun ? 'streaming' : 'ready'}
onRegenerate={handleRegenerate}
+ // Questions only. Editing the agent's own answer would
+ // put words in its mouth that its tool calls do not
+ // support, and deleting one alone would strand the
+ // results of the calls it made.
+ onEdit={
+ message.role === 'user'
+ ? handleEditQuestion
+ : undefined
+ }
+ onRetry={
+ message.role === 'user'
+ ? handleRetryQuestion
+ : undefined
+ }
+ onDelete={
+ message.role === 'user'
+ ? handleDeleteQuestion
+ : undefined
+ }
+ // Only the last message can show the live subagent row,
+ // so only it needs the runs.
+ subagents={
+ i === uiMessages.length - 1 ? subagents : undefined
+ }
reasoningContainerRef={reasoningContainerRef}
isReasoningAtBottom={isReasoningAtBottom}
onReasoningScroll={handleReasoningScroll}