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): faster ask card, answered asks in the transcript (#9446)

James Dam4d24accdb802
diff --git a/web-app/src/containers/CoworkAskCard.tsx b/web-app/src/containers/CoworkAskCard.tsx
index 2cd82bf22..446b6baeb 100644
--- a/web-app/src/containers/CoworkAskCard.tsx
+++ b/web-app/src/containers/CoworkAskCard.tsx
@@ -1,26 +1,62 @@
-import { useEffect, useMemo, useState } from 'react'
-import { ArrowRight, Check, ChevronLeft, ChevronRight, X } from 'lucide-react'
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+import {
+ ArrowRight,
+ Check,
+ ChevronLeft,
+ ChevronRight,
+ Pencil,
+ X,
+} from 'lucide-react'
+import { useIsPresent } from 'motion/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
import type { AskAnswer, AskRequestPayload } from '@/types/coworkSession'
+/** Pause between a single-select pick and moving to the next question. */
+const AUTO_ADVANCE_MS = 200
+
+/** Clicks this soon after an automatic jump are ignored (see `jumpedAtRef`). */
+const CLICK_GUARD_MS = 300
+
/** Sentinel for the free-text row; never a real option label. */
const OTHER = '\u0000other'
-/** Square check used by the option rows. No checkbox primitive exists in `ui/`. */
+/** Square check for multi-select rows. No checkbox primitive exists in `ui/`. */
function CheckSquare({ checked }: { checked: boolean }) {
return (
<span
+ aria-hidden
+ className="flex size-6 shrink-0 items-center justify-center"
+ >
+ <span
+ className={cn(
+ 'flex size-4 items-center justify-center rounded border transition-colors',
+ checked
+ ? 'border-primary bg-primary text-primary-foreground'
+ : 'border-main-view-fg/30'
+ )}
+ >
+ {checked && <Check size={11} strokeWidth={3} />}
+ </span>
+ </span>
+ )
+}
+
+/** Numbered badge for single-select rows; fills when selected. Matches the 1–9 shortcuts. */
+function NumberBadge({ n, checked }: { n: React.ReactNode; checked: boolean }) {
+ return (
+ <span
+ aria-hidden
className={cn(
- 'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors',
+ 'flex size-6 shrink-0 items-center justify-center rounded-md text-xs font-medium tabular-nums transition-colors',
checked
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-main-view-fg/30'
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-main-view-fg/10 text-main-view-fg/60'
)}
>
- {checked && <Check size={11} strokeWidth={3} />}
+ {n}
</span>
)
}
@@ -43,8 +79,62 @@ export function CoworkAskCard({
}) {
const { t } = useTranslation()
const [index, setIndex] = useState(0)
+ // Which way the last page change went, so the new question slides in from
+ // that side. Derived during render from the previous index (React's
+ // "storing information from previous renders" pattern); 0 on first render,
+ // so the opening question doesn't slide on top of the card's own entrance.
+ const [shownIndex, setShownIndex] = useState(index)
+ const [direction, setDirection] = useState(0)
+ if (index !== shownIndex) {
+ setShownIndex(index)
+ setDirection(index > shownIndex ? 1 : -1)
+ }
const [selected, setSelected] = useState<Record<string, string[]>>({})
const [custom, setCustom] = useState<Record<string, string>>({})
+ const otherInputRef = useRef<HTMLInputElement>(null)
+ const keyHandlerRef = useRef<((e: KeyboardEvent) => void) | null>(null)
+ const cardRef = useRef<HTMLDivElement>(null)
+ // The option row last pressed with a pointer. A clicked row keeps focus, so
+ // Enter there means "continue"; a row reached by Tab means "pick this one".
+ const pointerRowRef = useRef<Element | null>(null)
+ const autoAdvanceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ // When the last automatic jump landed. A click this soon after one is most
+ // likely the tail of a double-click on the previous page, and would
+ // otherwise answer the new question too; number keys are unaffected.
+ const jumpedAtRef = useRef(-Infinity)
+ const cancelAutoAdvance = () =>
+ clearTimeout(autoAdvanceRef.current ?? undefined)
+ // False while the card plays its exit animation (cowork.tsx wraps it in
+ // AnimatePresence). An exiting card is already answered, or belongs to a
+ // session the user switched away from, so it must stop taking input:
+ // no shortcuts, no pending jump, no focus grabs, and `inert` for the rest.
+ const isPresent = useIsPresent()
+ useEffect(() => {
+ if (!isPresent) clearTimeout(autoAdvanceRef.current ?? undefined)
+ }, [isPresent])
+ // Any page change (manual or the jump itself) cancels a pending jump, so
+ // paging away and back can't be followed by a surprise advance.
+ useEffect(
+ () => () => clearTimeout(autoAdvanceRef.current ?? undefined),
+ [index]
+ )
+ // Option picks set aside while free text is active, so clearing the text
+ // restores them instead of leaving the user with nothing selected.
+ const stashRef = useRef<Record<string, string[]>>({})
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => keyHandlerRef.current?.(e)
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [])
+
+ // Built later in render (it needs the question), but only installed once the
+ // render commits, so a discarded render can never leave a stale handler. It
+ // stays null on the early-return path below, which clears the old one.
+ let handleKey: ((e: KeyboardEvent) => void) | null = null
+ useLayoutEffect(() => {
+ keyHandlerRef.current = isPresent ? handleKey : null
+ })
// A new request is a clean slate; keeping prior picks would silently answer
// the next question with the previous one's selections.
@@ -52,6 +142,7 @@ export function CoworkAskCard({
setIndex(0)
setSelected({})
setCustom({})
+ stashRef.current = {}
}, [requestId])
const questions = request?.questions ?? []
@@ -62,13 +153,22 @@ export function CoworkAskCard({
if (picks.includes(OTHER)) return !!custom[qid]?.trim()
return picks.length > 0
}
- // The core rejects a response that doesn't answer every question exactly
- // once (`validate_results`), so submit stays closed until all are answered.
- const allAnswered = useMemo(
- () => questions.length > 0 && questions.every((q) => isAnswered(q.id)),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [questions, selected, custom]
- )
+
+ // The chat box autofocuses and would swallow the digits, so a new question
+ // takes focus itself — on arrival and on every page change, since the control
+ // that advanced (the arrow) may unmount and drop focus to the page. A chat
+ // box the user is already typing into keeps its focus and its text.
+ const hasQuestion = !!requestId && !!question
+ useEffect(() => {
+ if (!hasQuestion || !isPresent) return
+ const active = document.activeElement
+ const typing =
+ (active instanceof HTMLTextAreaElement ||
+ active instanceof HTMLInputElement) &&
+ !cardRef.current?.contains(active) &&
+ active.value.trim() !== ''
+ if (!typing) cardRef.current?.focus({ preventScroll: true })
+ }, [requestId, hasQuestion, index, isPresent])
if (!requestId || !question) return null
@@ -77,17 +177,31 @@ export function CoworkAskCard({
const usingCustom = picks.includes(OTHER)
const toggle = (label: string) => {
+ // Picking an option drops the free-text answer, so don't leave its text
+ // sitting in the input looking like the live answer.
+ if (picks.includes(OTHER)) {
+ setCustom((c) => ({ ...c, [question.id]: '' }))
+ const stashed = stashRef.current[question.id] ?? []
+ delete stashRef.current[question.id]
+ if (question.multi) {
+ // Bring the set-aside checks back and add this one, rather than losing them.
+ setSelected((prev) => ({
+ ...prev,
+ [question.id]: stashed.includes(label)
+ ? stashed
+ : [...stashed, label],
+ }))
+ return
+ }
+ }
setSelected((prev) => {
const current = prev[question.id] ?? []
// Free text is exclusive with options: the contract allows one or the
// other on a `QuestionResult`, never both.
- if (label === OTHER) {
- return { ...prev, [question.id]: current.includes(OTHER) ? [] : [OTHER] }
- }
const withoutOther = current.filter((l) => l !== OTHER)
- if (!question.multi) {
- return { ...prev, [question.id]: withoutOther.includes(label) ? [] : [label] }
- }
+ // Radio semantics: picking again keeps the pick, so pressing the same
+ // number twice can't silently clear the answer.
+ if (!question.multi) return { ...prev, [question.id]: [label] }
return {
...prev,
[question.id]: withoutOther.includes(label)
@@ -95,6 +209,17 @@ export function CoworkAskCard({
: [...withoutOther, label],
}
})
+ // A single-select pick is the whole answer, so move on to the next question
+ // after a beat that lets the pick register. The last question waits for an
+ // explicit continue, since submitting can't be undone.
+ if (!question.multi && !isLast) {
+ cancelAutoAdvance()
+ const from = index
+ autoAdvanceRef.current = setTimeout(() => {
+ jumpedAtRef.current = performance.now()
+ setIndex(from + 1)
+ }, AUTO_ADVANCE_MS)
+ }
}
const submit = () => {
@@ -104,20 +229,141 @@ export function CoworkAskCard({
const answer = selected[q.id] ?? []
return answer.includes(OTHER)
? { id: q.id, selected: [], custom_input: custom[q.id]?.trim() }
- : { id: q.id, selected: answer }
+ : {
+ id: q.id,
+ // Option order, not click order, so the answer reads like the list.
+ selected: q.options
+ .map((o) => o.label)
+ .filter((l) => answer.includes(l)),
+ }
})
)
}
- const advance = () => (isLast ? submit() : setIndex((i) => i + 1))
+ // The core rejects a response that doesn't answer every question exactly
+ // once (`validate_results`), so submit waits until all are answered.
+ const firstUnanswered = questions.findIndex((q) => !isAnswered(q.id))
+ const openElsewhere = questions.some(
+ (q, i) => i !== index && !isAnswered(q.id)
+ )
+ // On the last page with an earlier question still open (the user paged ahead),
+ // continuing takes them to it rather than leaving a disabled dead end.
+ const advance = () => {
+ if (!isLast) setIndex((i) => i + 1)
+ else if (firstUnanswered === -1) submit()
+ else setIndex(firstUnanswered)
+ }
+
+ // Enter continues once this question is answered. Single-select also gets 1–9
+ // to pick the matching option, and the number after the last option focuses
+ // the free-text row. Ignored while typing so digits still reach inputs.
+ handleKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.isComposing || e.repeat) return
+ if (e.metaKey || e.ctrlKey || e.altKey) return
+ const el = e.target instanceof HTMLElement ? e.target : null
+ // Only act when focus is on the page itself or inside this card; a press on
+ // a sidebar button or link elsewhere must not change the pending answer.
+ if (el && el !== document.body && !cardRef.current?.contains(el)) return
+ if (
+ el &&
+ (['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName) ||
+ el.isContentEditable ||
+ el.closest(
+ '[role=textbox],[role=combobox],[role=listbox],[role=menu],[role=dialog],[role=slider]'
+ ))
+ ) {
+ return
+ }
+ // Keyboard-only path: after a pick, Enter continues. Handled on the page,
+ // on a row the user clicked (a clicked row keeps focus, and its native
+ // Enter would re-toggle it), or on the ticked radio. Enter on any other row
+ // keeps its native meaning — pick or untick that row — so it never submits
+ // a different answer than the one the user is looking at.
+ if (e.key === 'Enter') {
+ const onPage =
+ !el ||
+ el === document.body ||
+ el === cardRef.current ||
+ el === pointerRowRef.current ||
+ // A ticked radio is the answer itself, so Enter on it continues. A
+ // ticked checkbox is not: Enter there must untick it as usual.
+ (el.getAttribute('role') === 'radio' &&
+ el.getAttribute('aria-checked') === 'true')
+ if (onPage && isAnswered(question.id)) {
+ e.preventDefault()
+ advance()
+ }
+ return
+ }
+ if (question.multi || !/^[1-9]$/.test(e.key)) return
+ const n = Number(e.key)
+ if (n <= question.options.length) {
+ e.preventDefault()
+ toggle(question.options[n - 1].label)
+ } else if (n === question.options.length + 1) {
+ e.preventDefault()
+ otherInputRef.current?.focus()
+ }
+ }
// Declining resolves the whole request as cancelled — the core has no
// per-question skip, since every question must come back answered.
const decline = () => onRespond(requestId, null)
+ const answered = isAnswered(question.id)
+ const canAdvance = answered
+ // Typed text replaces the option picks (the contract allows one or the other),
+ // so the options recede — for multi-select too, where the unticking is
+ // otherwise easy to miss.
+ const dimOptions = usingCustom
+
+ const iconButton =
+ 'rounded p-1 hover:text-main-view-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-30'
+
+ const skipButton = (
+ <Button variant="ghost" size="sm" className="h-7" onClick={decline}>
+ {t('common:skip')}
+ </Button>
+ )
+ const continueButton = (
+ <Button
+ size="icon-sm"
+ className="rounded-md"
+ disabled={!canAdvance}
+ // Distinct from the chevron's `askNext`: that only pages the view,
+ // this is the primary action (record this answer, then move on).
+ aria-label={
+ isLast && !openElsewhere ? t('common:submit') : t('common:askContinue')
+ }
+ onClick={advance}
+ >
+ <ArrowRight size={14} />
+ </Button>
+ )
+
return (
- <div className="mb-2 rounded-lg border bg-main-view">
- <div className="flex items-start gap-2 px-3 pt-2.5 pb-2">
- <p className="min-w-0 flex-1 text-sm font-medium">{question.question}</p>
+ <div
+ ref={cardRef}
+ tabIndex={-1}
+ inert={!isPresent}
+ role="group"
+ aria-label={
+ questions.length > 1
+ ? `${question.question} (${t('common:askPageOf', { current: index + 1, total: questions.length })})`
+ : question.question
+ }
+ className="mb-2 rounded-lg border bg-main-view outline-none"
+ >
+ <div className="flex items-start gap-2 px-4 pt-3 pb-1.5">
+ <p
+ key={index}
+ className={cn(
+ 'min-w-0 flex-1 text-sm font-medium',
+ direction !== 0 &&
+ 'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-200'
+ )}
+ >
+ {question.question}
+ </p>
<div className="flex shrink-0 items-center gap-0.5 text-main-view-fg/50">
{questions.length > 1 && (
<>
@@ -126,19 +372,24 @@ export function CoworkAskCard({
onClick={() => setIndex((i) => Math.max(0, i - 1))}
disabled={index === 0}
aria-label={t('common:askPrev')}
- className="rounded p-0.5 hover:text-main-view-fg disabled:opacity-30"
+ className={iconButton}
>
<ChevronLeft size={14} />
</button>
<span className="px-0.5 text-xs tabular-nums">
- {index + 1}/{questions.length}
+ {t('common:askPageOf', {
+ current: index + 1,
+ total: questions.length,
+ })}
</span>
<button
type="button"
- onClick={() => setIndex((i) => Math.min(questions.length - 1, i + 1))}
+ onClick={() =>
+ setIndex((i) => Math.min(questions.length - 1, i + 1))
+ }
disabled={isLast}
aria-label={t('common:askNext')}
- className="rounded p-0.5 hover:text-main-view-fg disabled:opacity-30"
+ className={iconButton}
>
<ChevronRight size={14} />
</button>
@@ -148,94 +399,192 @@ export function CoworkAskCard({
type="button"
onClick={decline}
aria-label={t('common:close')}
- className="ml-0.5 rounded p-0.5 hover:text-main-view-fg"
+ className={cn(iconButton, 'ml-1')}
>
<X size={14} />
</button>
</div>
</div>
- <div className="flex flex-col gap-0.5 px-2 pb-1">
- {question.options.map((option, i) => {
- const checked = picks.includes(option.label)
- return (
- <button
- key={option.label}
- type="button"
- onClick={() => toggle(option.label)}
- title={option.description}
- className="flex items-start gap-2 rounded-md px-2 py-1.5 text-left hover:bg-main-view-fg/5"
- >
- <CheckSquare checked={checked} />
- <span className="min-w-0 flex-1">
- <span className="text-[13px] leading-5">{option.label}</span>
- {question.recommended === i && (
- <span className="ml-1.5 text-[11px] text-main-view-fg/45">
- {t('common:askRecommended')}
- </span>
+ {/* Keyed by page so each question mounts fresh and plays the slide. */}
+ <div
+ key={index}
+ className={cn(
+ direction !== 0 &&
+ 'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-200 motion-safe:ease-out',
+ direction > 0 && 'motion-safe:slide-in-from-right-2',
+ direction < 0 && 'motion-safe:slide-in-from-left-2'
+ )}
+ >
+ <div
+ role={question.multi ? 'group' : 'radiogroup'}
+ aria-label={question.question}
+ // Capped so a long list can't push the chat box off screen.
+ className="flex max-h-[45vh] flex-col overflow-y-auto px-2"
+ >
+ {question.options.map((option, i) => {
+ const checked = picks.includes(option.label)
+ return (
+ // The hairline sits on a flat wrapper so the row's rounded hover
+ // fill doesn't curl its ends.
+ <div
+ key={option.label}
+ className={cn(
+ 'border-b border-main-view-fg/5 py-px last:border-b-0',
+ // No hairline touching a filled row (picked or hovered): drop
+ // this wrapper's own line and the one on the row above it.
+ 'has-[>button[aria-checked=true]]:border-transparent has-[>button:hover]:border-transparent',
+ '[&:has(+div>button[aria-checked=true])]:border-transparent [&:has(+div>button:hover)]:border-transparent'
)}
- {option.description && (
- <span className="block text-[11px] leading-4 text-main-view-fg/50">
- {option.description}
+ >
+ <button
+ type="button"
+ role={question.multi ? 'checkbox' : 'radio'}
+ aria-checked={checked}
+ aria-keyshortcuts={
+ question.multi || i > 8 ? undefined : String(i + 1)
+ }
+ onPointerDown={(e) =>
+ (pointerRowRef.current = e.currentTarget)
+ }
+ // Leaving the row ends "clicked": coming back by Tab is a
+ // keyboard visit, where Enter must act on the row itself.
+ onBlur={(e) => {
+ if (pointerRowRef.current === e.currentTarget)
+ pointerRowRef.current = null
+ }}
+ onClick={() => {
+ if (
+ performance.now() - jumpedAtRef.current <
+ CLICK_GUARD_MS
+ )
+ return
+ toggle(option.label)
+ }}
+ className={cn(
+ 'flex w-full items-start gap-3 rounded-lg px-2 py-2 text-left transition-[opacity,background-color] hover:bg-main-view-fg/5',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
+ checked && 'bg-main-view-fg/5',
+ dimOptions &&
+ 'opacity-50 hover:opacity-100 focus-visible:opacity-100'
+ )}
+ >
+ {question.multi ? (
+ <CheckSquare checked={checked} />
+ ) : (
+ // Only 1–9 have key shortcuts; past that a number would read as a
+ // shortcut that doesn't exist.
+ <NumberBadge n={i < 9 ? i + 1 : '·'} checked={checked} />
+ )}
+ {/* leading-6 matches the 24px badge so the label centres on it. */}
+ <span className="min-w-0 flex-1 leading-6">
+ <span className="text-[13px]">{option.label}</span>
+ {question.recommended === i && (
+ // The leading space keeps the accessible name from running
+ // "label.Recommended" together.
+ <span className="ml-1 text-[11px] text-main-view-fg/60">
+ {' '}
+ {t('common:askRecommended')}
+ </span>
+ )}
+ {option.description && (
+ <span className="block text-[11px] leading-4 text-main-view-fg/60">
+ {option.description}
+ </span>
+ )}
</span>
- )}
- </span>
- </button>
- )
- })}
- <button
- type="button"
- onClick={() => toggle(OTHER)}
- className={cn(
- 'flex items-start gap-2 rounded-md px-2 py-1.5 text-left hover:bg-main-view-fg/5',
- usingCustom && 'bg-main-view-fg/5'
- )}
- >
- <CheckSquare checked={usingCustom} />
- <span className="text-[13px] leading-5">{t('common:askSomethingElse')}</span>
- </button>
- {usingCustom && (
- <Input
- autoFocus
- value={custom[question.id] ?? ''}
- onChange={(e) =>
- setCustom((prev) => ({ ...prev, [question.id]: e.target.value }))
- }
- onKeyDown={(e) => {
- if (e.key === 'Enter' && isAnswered(question.id)) {
- e.preventDefault()
- advance()
- }
- }}
- placeholder={t('common:askSomethingElsePlaceholder')}
- className="mx-1 mb-1 h-8"
- />
- )}
- </div>
+ </button>
+ </div>
+ )
+ })}
+ </div>
- <div className="flex items-center gap-2 border-t px-3 py-2">
- <span className="text-xs text-main-view-fg/50">
- {question.multi || picks.length > 0
- ? t('common:askSelectedCount', { count: picks.filter((p) => p !== OTHER).length })
- : null}
- </span>
- <div className="ml-auto flex items-center gap-1.5">
- <Button variant="ghost" size="sm" className="h-7" onClick={decline}>
- {t('common:skip')}
- </Button>
- <Button
- size="icon-sm"
- className="rounded-full"
- disabled={isLast ? !allAnswered : !isAnswered(question.id)}
- // Distinct from the chevron's `askNext`: that only pages the view,
- // this is the primary action (record this answer, then move on).
- aria-label={isLast ? t('common:submit') : t('common:askContinue')}
- onClick={advance}
+ {/* Always-visible row (like Claude's ask card) so it's obvious users can
+ type their own answer. Its leading mark matches the option rows: a
+ pencil badge for single-select, a checkbox for multi-select. */}
+ <div className="px-2 pt-1 pb-2">
+ <div
+ onClick={() => otherInputRef.current?.focus()}
+ className={cn(
+ 'flex h-11 cursor-text items-center gap-3 rounded-lg px-2 transition-colors',
+ usingCustom
+ ? 'bg-main-view-fg/8'
+ : 'bg-main-view-fg/4 focus-within:bg-main-view-fg/8'
+ )}
>
- <ArrowRight size={14} />
- </Button>
+ {question.multi ? (
+ <CheckSquare checked={usingCustom} />
+ ) : (
+ <NumberBadge n={<Pencil size={12} />} checked={false} />
+ )}
+ <Input
+ ref={otherInputRef}
+ value={custom[question.id] ?? ''}
+ // Heading for the free-text row means the pick wasn't the final
+ // answer, so a jump queued by it must not pull the user away.
+ onFocus={cancelAutoAdvance}
+ onChange={(e) => {
+ cancelAutoAdvance()
+ const value = e.target.value
+ setCustom((prev) => ({ ...prev, [question.id]: value }))
+ // Real text selects the free-text answer (exclusive with options, per
+ // the QuestionResult contract); the prior picks are stashed and come
+ // back when the text is cleared. Blank text never touches picks.
+ if (value.trim()) {
+ if (!picks.includes(OTHER))
+ stashRef.current[question.id] = picks
+ setSelected((prev) => ({ ...prev, [question.id]: [OTHER] }))
+ } else if (picks.includes(OTHER)) {
+ const restored = stashRef.current[question.id] ?? []
+ delete stashRef.current[question.id]
+ setSelected((prev) => ({ ...prev, [question.id]: restored }))
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ // Confirming an IME composition must not advance or submit.
+ if (e.nativeEvent.isComposing || e.keyCode === 229) return
+ e.preventDefault()
+ if (answered) {
+ e.currentTarget.blur()
+ advance()
+ }
+ } else if (e.key === 'Escape') {
+ e.currentTarget.blur()
+ }
+ }}
+ placeholder={t('common:askSomethingElse')}
+ aria-label={t('common:askSomethingElse')}
+ aria-keyshortcuts={
+ question.multi || question.options.length > 8
+ ? undefined
+ : String(question.options.length + 1)
+ }
+ className="h-8 flex-1 border-0 bg-transparent px-0 text-[13px] shadow-none focus-visible:ring-0 md:text-[13px] dark:bg-transparent"
+ />
+ {/* Single-select keeps its actions in this row: Skip until there is an
+ answer, then the continue arrow. Multi-select uses the footer. */}
+ {!question.multi && (
+ <div
+ className="flex shrink-0 items-center"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {answered ? continueButton : skipButton}
+ </div>
+ )}
+ </div>
</div>
</div>
+
+ {question.multi && (
+ <div className="flex items-center gap-1.5 border-t px-4 py-2">
+ <span className="flex-1 text-xs text-main-view-fg/50">
+ {t('common:askSelectedCount', { count: picks.length })}
+ </span>
+ {skipButton}
+ {continueButton}
+ </div>
+ )}
</div>
)
}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index e79be83fe..063d8dba4 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -6,6 +6,9 @@ import { cn } from '@/lib/utils'
import { usedSkillNames } from '@/lib/agentActivity'
import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'
+import { AskSummaryCard } from './message/AskSummaryCard'
+import { summarizeAsk } from '@/lib/coworkAsk'
+import { ASK_TOOL_NAME } from '@/lib/coworkTools'
import {
CHAT_STATUS,
CONTENT_TYPE,
@@ -485,6 +488,18 @@ export const MessageItem = memo(
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
const t = part.type
+ // A settled ask leaves the trace as a Q&A card, so the answers stay in
+ // view instead of being folded into "Worked for…".
+ if (t === `tool-${ASK_TOOL_NAME}` && part.state === 'output-available') {
+ const rows = summarizeAsk(part.input, part.output)
+ if (rows) {
+ flushCot(true)
+ elements.push(
+ <AskSummaryCard key={`${message.id}-ask-${i}`} rows={rows} />
+ )
+ continue
+ }
+ }
if (isCotPart(t)) {
cotEntries.push({ part, index: i })
continue
diff --git a/web-app/src/containers/__tests__/CoworkAskCard.test.tsx b/web-app/src/containers/__tests__/CoworkAskCard.test.tsx
index e0bafd6d3..c51a1d795 100644
--- a/web-app/src/containers/__tests__/CoworkAskCard.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkAskCard.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, fireEvent } from '@testing-library/react'
+import { render, screen, fireEvent, act } from '@testing-library/react'
import '@testing-library/jest-dom'
import { CoworkAskCard } from '@/containers/CoworkAskCard'
import type { AskRequestPayload } from '@/hooks/useCoworkRun'
@@ -45,6 +45,10 @@ beforeEach(() => {
})
const submitButton = () => screen.getByLabelText('common:submit')
+// Single-select shows Skip in the free-text row until there is an answer; the
+// continue arrow only appears once one exists.
+const expectNoSubmit = () =>
+ expect(screen.queryByLabelText('common:submit')).not.toBeInTheDocument()
describe('CoworkAskCard', () => {
it('renders nothing when there is no pending request', () => {
@@ -82,8 +86,7 @@ describe('CoworkAskCard', () => {
it('free text and options are mutually exclusive, per the QuestionResult contract', () => {
render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
fireEvent.click(screen.getByText('Small'))
- fireEvent.click(screen.getByText('common:askSomethingElse'))
- fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElse'), {
target: { value: 'neither' },
})
fireEvent.click(submitButton())
@@ -95,11 +98,30 @@ describe('CoworkAskCard', () => {
it('cannot submit on empty free text', () => {
render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
- fireEvent.click(screen.getByText('common:askSomethingElse'))
- expect(submitButton()).toBeDisabled()
- fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {
+ expectNoSubmit()
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElse'), {
target: { value: ' ' },
})
+ expectNoSubmit()
+ })
+
+ it('shows the free-text input up front, without clicking anything', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ expect(screen.getByPlaceholderText('common:askSomethingElse')).toBeInTheDocument()
+ })
+
+ it('single-select shows numbers and the number keys pick an option', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ expect(screen.getByText('1')).toBeInTheDocument()
+ fireEvent.keyDown(window, { key: '2' })
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Large'] }])
+ })
+
+ it('multi-select keeps checkboxes (no numbers) and ignores number keys', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ expect(screen.queryByText('1')).not.toBeInTheDocument()
+ fireEvent.keyDown(window, { key: '1' })
expect(submitButton()).toBeDisabled()
})
@@ -109,7 +131,7 @@ describe('CoworkAskCard', () => {
fireEvent.click(screen.getByText('A1'))
fireEvent.click(screen.getByLabelText('common:askNext'))
expect(screen.getByText('Second?')).toBeInTheDocument()
- expect(submitButton()).toBeDisabled()
+ expectNoSubmit()
fireEvent.click(screen.getByText('B1'))
fireEvent.click(submitButton())
@@ -119,6 +141,303 @@ describe('CoworkAskCard', () => {
])
})
+ it('blank text never wipes an option pick', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Small'))
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElse'), {
+ target: { value: ' ' },
+ })
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Small'] }])
+ })
+
+ it('picking an option clears leftover free text', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ const input = screen.getByPlaceholderText('common:askSomethingElse') as HTMLInputElement
+ fireEvent.change(input, { target: { value: 'foo' } })
+ fireEvent.click(screen.getByText('Large'))
+ expect(input.value).toBe('')
+ })
+
+ it('the number after the last option focuses the free-text input', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.keyDown(window, { key: '3' })
+ expect(screen.getByPlaceholderText('common:askSomethingElse')).toHaveFocus()
+ })
+
+ it('ignores digits typed into other inputs, with modifiers, or out of range', () => {
+ render(
+ <>
+ <textarea data-testid="chat" />
+ <CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />
+ </>
+ )
+ fireEvent.keyDown(screen.getByTestId('chat'), { key: '1' })
+ fireEvent.keyDown(window, { key: '1', metaKey: true })
+ fireEvent.keyDown(window, { key: '9' })
+ expectNoSubmit()
+ })
+
+ it('Enter in the input does not submit while an earlier question is unanswered', () => {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.click(screen.getByLabelText('common:askNext'))
+ const input = screen.getByPlaceholderText('common:askSomethingElse')
+ fireEvent.change(input, { target: { value: 'typed' } })
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
+ it('Enter during IME composition does not advance', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ const input = screen.getByPlaceholderText('common:askSomethingElse')
+ fireEvent.change(input, { target: { value: 'x' } })
+ fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
+ it('Enter on the page continues after a number pick', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.keyDown(window, { key: '1' })
+ fireEvent.keyDown(document.body, { key: 'Enter' })
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Small'] }])
+ })
+
+ it('multi-select picks come back when the free text is cleared', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Team'))
+ const input = screen.getByPlaceholderText('common:askSomethingElse')
+ fireEvent.change(input, { target: { value: 'x' } })
+ fireEvent.change(input, { target: { value: '' } })
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'who', selected: ['Team'] }])
+ })
+
+ it('clicking an option while free text is active restores the stashed multi picks', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Team'))
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElse'), {
+ target: { value: 'x' },
+ })
+ fireEvent.click(screen.getByText('Public'))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [
+ { id: 'who', selected: ['Team', 'Public'] },
+ ])
+ })
+
+ it('never numbers the free-text field (it shows a pencil), even past 9 options', () => {
+ const many: AskRequestPayload = {
+ questions: [
+ {
+ id: 'm',
+ question: 'Pick?',
+ options: Array.from({ length: 9 }, (_, i) => ({ label: `Opt${i + 1}` })),
+ },
+ ],
+ }
+ render(<CoworkAskCard requestId="ask-1" request={many} onRespond={onRespond} />)
+ expect(screen.queryByText('10')).not.toBeInTheDocument()
+ })
+
+ it('counts free text as the one selection, since it replaces the picks', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText(multi.questions[0].options[0].label))
+ fireEvent.click(screen.getByText(multi.questions[0].options[1].label))
+ expect(screen.getByText('2 selected')).toBeInTheDocument()
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElse'), {
+ target: { value: 'x' },
+ })
+ expect(screen.getByText('1 selected')).toBeInTheDocument()
+ })
+
+ it('groups the options with an accessible name', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ expect(screen.getByRole('radiogroup', { name: 'Which scope?' })).toBeInTheDocument()
+ })
+
+ it('Enter on a mouse-focused option continues with the number-picked answer', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ const small = screen.getByText('Small').closest('button')!
+ fireEvent.pointerDown(small)
+ fireEvent.click(small)
+ small.focus()
+ fireEvent.keyDown(small, { key: '2' })
+ fireEvent.keyDown(small, { key: 'Enter' })
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Large'] }])
+ })
+
+ it('Enter on a row reached by keyboard picks that row instead of submitting the earlier pick', () => {
+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.keyDown(window, { key: '1' })
+ const large = screen.getByText('Large').closest('button')!
+ large.focus()
+ fireEvent.keyDown(large, { key: 'Enter' })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
+ it('Enter on a ticked checkbox reached by keyboard unticks it rather than submitting', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ const [first, second] = multi.questions[0].options.map((o) => o.label)
+ fireEvent.click(screen.getByText(second))
+ const row = screen.getByText(first).closest('button')!
+ fireEvent.click(row)
+ row.focus()
+ fireEvent.keyDown(row, { key: 'Enter' })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
+ it('a clicked row reached again by Tab gets its native Enter back', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ const row = screen.getByText(multi.questions[0].options[0].label).closest('button')!
+ fireEvent.pointerDown(row)
+ fireEvent.click(row)
+ row.focus()
+ row.blur()
+ row.focus()
+ fireEvent.keyDown(row, { key: 'Enter' })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
+ it('submits multi-select picks in option order, not click order', () => {
+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ const [first, second] = multi.questions[0].options.map((o) => o.label)
+ fireEvent.click(screen.getByText(second))
+ fireEvent.click(screen.getByText(first))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [
+ { id: multi.questions[0].id, selected: [first, second] },
+ ])
+ })
+
+ it('on the last page, continue jumps back to an unanswered earlier question', () => {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.click(screen.getByLabelText('common:askNext'))
+ fireEvent.click(screen.getByText('B1'))
+ fireEvent.click(screen.getByLabelText('common:askContinue'))
+ expect(onRespond).not.toHaveBeenCalled()
+ expect(screen.getByText('First?')).toBeInTheDocument()
+ })
+
+ it('moves to the next question after a single-select pick, but not past the last', () => {
+ vi.useFakeTimers()
+ try {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.keyDown(window, { key: '1' })
+ act(() => vi.advanceTimersByTime(250))
+ expect(screen.getByText('Second?')).toBeInTheDocument()
+
+ fireEvent.keyDown(window, { key: '2' })
+ act(() => vi.advanceTimersByTime(250))
+ expect(screen.getByText('Second?')).toBeInTheDocument()
+ expect(onRespond).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('ignores a click that lands right after an automatic jump (double-click tail)', () => {
+ vi.useFakeTimers()
+ try {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ act(() => vi.advanceTimersByTime(400))
+ fireEvent.click(screen.getByText('A1'))
+ act(() => vi.advanceTimersByTime(250))
+ expect(screen.getByText('Second?')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('B1'))
+ expect(screen.getByText('B1').closest('button')).toHaveAttribute('aria-checked', 'false')
+ act(() => vi.advanceTimersByTime(400))
+ fireEvent.click(screen.getByText('B1'))
+ expect(screen.getByText('B1').closest('button')).toHaveAttribute('aria-checked', 'true')
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('never auto-advances a multi-select pick', () => {
+ vi.useFakeTimers()
+ try {
+ const request: AskRequestPayload = {
+ questions: [
+ { ...multi.questions[0], id: 'm' },
+ { id: 'b', question: 'Second?', options: [{ label: 'B1' }, { label: 'B2' }] },
+ ],
+ }
+ render(<CoworkAskCard requestId="ask-1" request={request} onRespond={onRespond} />)
+ act(() => vi.advanceTimersByTime(400))
+ fireEvent.click(screen.getByText(multi.questions[0].options[0].label))
+ act(() => vi.advanceTimersByTime(400))
+ expect(screen.getByText(multi.questions[0].question)).toBeInTheDocument()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('drops the pending jump when the user heads for the free-text row', () => {
+ vi.useFakeTimers()
+ try {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.keyDown(window, { key: '1' })
+ const input = screen.getByPlaceholderText('common:askSomethingElse')
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: 'my own' } })
+ act(() => vi.advanceTimersByTime(250))
+ expect(screen.getByText('First?')).toBeInTheDocument()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('drops the pending jump if the user pages away first', () => {
+ vi.useFakeTimers()
+ try {
+ render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('A1'))
+ fireEvent.click(screen.getByLabelText('common:askNext'))
+ fireEvent.click(screen.getByLabelText('common:askPrev'))
+ act(() => vi.advanceTimersByTime(250))
+ expect(screen.getByText('First?')).toBeInTheDocument()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('ignores digits when focus is on a control outside the card', () => {
+ render(
+ <>
+ <button data-testid="outside">sidebar</button>
+ <CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />
+ </>
+ )
+ const outside = screen.getByTestId('outside')
+ outside.focus()
+ fireEvent.keyDown(outside, { key: '1' })
+ expectNoSubmit()
+ })
+
+ it('takes focus when a question appears so number keys work over an autofocused chat box', () => {
+ render(
+ <>
+ <textarea data-testid="chat" autoFocus />
+ <CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />
+ </>
+ )
+ const card = screen.getByRole('radiogroup').closest<HTMLElement>('[tabindex="-1"]')!
+ expect(card).toHaveFocus()
+ fireEvent.keyDown(card, { key: '2' })
+ fireEvent.keyDown(card, { key: 'Enter' })
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Large'] }])
+ })
+
+ it('removes the key listener on unmount', () => {
+ const { unmount } = render(
+ <CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />
+ )
+ unmount()
+ fireEvent.keyDown(window, { key: '1' })
+ fireEvent.keyDown(document.body, { key: 'Enter' })
+ expect(onRespond).not.toHaveBeenCalled()
+ })
+
it('Skip declines the whole request (the core has no per-question skip)', () => {
render(<CoworkAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
fireEvent.click(screen.getByText('common:skip'))
@@ -138,6 +457,6 @@ describe('CoworkAskCard', () => {
fireEvent.click(screen.getByText('Small'))
// A second request must not inherit the first one's pick.
rerender(<CoworkAskCard requestId="ask-2" request={single} onRespond={onRespond} />)
- expect(submitButton()).toBeDisabled()
+ expectNoSubmit()
})
})
diff --git a/web-app/src/containers/message/AskSummaryCard.tsx b/web-app/src/containers/message/AskSummaryCard.tsx
new file mode 100644
index 000000000..107b1ba76
--- /dev/null
+++ b/web-app/src/containers/message/AskSummaryCard.tsx
@@ -0,0 +1,25 @@
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import type { AskSummaryRow } from '@/lib/coworkAsk'
+
+/**
+ * A settled `ask`, kept in the transcript so the user's answers stay visible
+ * once the card above the input closes. It replaces the tool call's entry in
+ * the reasoning trace (MessageItem skips the part after rendering this).
+ */
+export function AskSummaryCard({ rows }: { rows: AskSummaryRow[] }) {
+ const { t } = useTranslation()
+ return (
+ <div className="my-2 flex flex-col gap-3 rounded-lg border px-4 py-3 text-sm">
+ {rows.map((row, i) => (
+ <div key={i} className="flex flex-col gap-1">
+ <p className="text-main-view-fg/60">{row.question}</p>
+ {row.answer === null ? (
+ <p className="text-main-view-fg/55">{t('common:askSkipped')}</p>
+ ) : (
+ <p className="whitespace-pre-wrap">{row.answer}</p>
+ )}
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/web-app/src/lib/__tests__/coworkAsk.test.ts b/web-app/src/lib/__tests__/coworkAsk.test.ts
index 0d5453ea0..28c5cee23 100644
--- a/web-app/src/lib/__tests__/coworkAsk.test.ts
+++ b/web-app/src/lib/__tests__/coworkAsk.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { parseAskRequest, renderAskResult } from '../coworkAsk'
+import { parseAskRequest, renderAskResult, summarizeAsk } from '../coworkAsk'
const q = (over = {}) => ({
id: 'q1',
@@ -68,3 +68,100 @@ describe('renderAskResult', () => {
expect(out.isError).toBeUndefined()
})
})
+
+describe('parseAskRequest hardening', () => {
+ type Parsed = { questions: Array<{ options: { label: string }[]; recommended?: number }> }
+
+ it('rejects duplicate question ids and duplicate option labels', () => {
+ expect(typeof parseAskRequest({ questions: [q(), q()] })).toBe('string')
+ expect(
+ typeof parseAskRequest({
+ questions: [q({ options: [{ label: 'A' }, { label: 'A' }] })],
+ })
+ ).toBe('string')
+ })
+
+ it('keeps recommended on the same option when a blank one is dropped', () => {
+ const out = parseAskRequest({
+ questions: [
+ q({ options: [{ label: '' }, { label: 'A' }, { label: 'B' }], recommended: 1 }),
+ ],
+ }) as Parsed
+ expect(out.questions[0].options[out.questions[0].recommended!].label).toBe('A')
+ })
+
+ it('keeps recommended on the same option past several dropped blanks', () => {
+ const out = parseAskRequest({
+ questions: [
+ q({
+ options: [{ label: '' }, { label: ' ' }, { label: 'A' }, { label: 'B' }],
+ recommended: 2,
+ }),
+ ],
+ }) as Parsed
+ expect(out.questions[0].options[out.questions[0].recommended!].label).toBe('A')
+ })
+
+ it('drops a label that is only the "(Recommended)" suffix', () => {
+ const out = parseAskRequest({
+ questions: [
+ q({ options: [{ label: '(Recommended)' }, { label: 'A' }, { label: 'B' }] }),
+ ],
+ }) as Parsed
+ expect(out.questions[0].options.map((o) => o.label)).toEqual(['A', 'B'])
+ expect(out.questions[0].recommended).toBeUndefined()
+ })
+
+ it('drops an out-of-range recommended index', () => {
+ const out = parseAskRequest({ questions: [q({ recommended: 7 })] }) as Parsed
+ expect(out.questions[0].recommended).toBeUndefined()
+ })
+
+ it('reads a "(Recommended)" label suffix as the field and strips it', () => {
+ const out = parseAskRequest({
+ questions: [q({ options: [{ label: 'A' }, { label: 'B (Recommended)' }] })],
+ }) as Parsed
+ expect(out.questions[0].options.map((o) => o.label)).toEqual(['A', 'B'])
+ expect(out.questions[0].recommended).toBe(1)
+ })
+})
+
+describe('summarizeAsk', () => {
+ const input = {
+ questions: [q(), q({ id: 'q2', question: 'Which ones?', multi: true })],
+ }
+
+ it('pairs each question with its picks, joining multi-select labels', () => {
+ const output = renderAskResult([
+ { id: 'q1', selected: ['A'] },
+ { id: 'q2', selected: ['A', 'B'] },
+ ]).output
+ expect(summarizeAsk(input, output)).toEqual([
+ { question: 'Which?', answer: 'A' },
+ { question: 'Which ones?', answer: 'A, B' },
+ ])
+ })
+
+ it('shows free text in place of picks', () => {
+ const output = renderAskResult([
+ { id: 'q1', selected: [], custom_input: ' my own ' },
+ { id: 'q2', selected: ['B'] },
+ ]).output
+ expect(summarizeAsk(input, output)?.[0].answer).toBe('my own')
+ })
+
+ it('marks every question unanswered when the card was dismissed', () => {
+ const output = renderAskResult(null).output
+ expect(summarizeAsk(input, output)?.map((r) => r.answer)).toEqual([null, null])
+ })
+
+ it('does not pass off a partial answer set as skips', () => {
+ const output = renderAskResult([{ id: 'q1', selected: ['A'] }]).output
+ expect(summarizeAsk(input, output)).toBeNull()
+ })
+
+ it('gives up on output it cannot read', () => {
+ expect(summarizeAsk(input, 'not json')).toBeNull()
+ expect(summarizeAsk({}, '[]')).toBeNull()
+ })
+})
diff --git a/web-app/src/lib/coworkAsk.ts b/web-app/src/lib/coworkAsk.ts
index 71ac31cd1..c49fc8eec 100644
--- a/web-app/src/lib/coworkAsk.ts
+++ b/web-app/src/lib/coworkAsk.ts
@@ -13,6 +13,8 @@ import type { ToolOutcome } from '@/lib/coworkRunner'
* the user thinks — unlike the Rust loop, which blocked inside the turn.
*/
+const RECOMMENDED_SUFFIX = /\s*\(recommended\)\s*$/i
+
/** Reject a malformed request rather than rendering an unanswerable card. */
export function parseAskRequest(input: unknown): AskRequestPayload | string {
const raw = (input ?? {}) as { questions?: unknown }
@@ -20,37 +22,62 @@ export function parseAskRequest(input: unknown): AskRequestPayload | string {
return '`ask` requires a non-empty `questions` array'
}
const questions: AskQuestion[] = []
+ const ids = new Set<string>()
for (const entry of raw.questions) {
const q = entry as Partial<AskQuestion>
if (typeof q.id !== 'string' || !q.id.trim()) {
return 'each question requires a non-empty `id`'
}
+ // Answers are keyed by id, so a repeat would make two questions share one.
+ if (ids.has(q.id)) return `duplicate question id '${q.id}'`
+ ids.add(q.id)
if (typeof q.question !== 'string' || !q.question.trim()) {
return `question '${q.id}' requires a \`question\` string`
}
if (!Array.isArray(q.options) || q.options.length < 2) {
return `question '${q.id}' requires at least two options`
}
- const options = q.options
- .map((o) => o as { label?: unknown; description?: unknown })
- .filter((o) => typeof o.label === 'string' && o.label.trim())
- .map((o) => ({
- label: o.label as string,
+ const requested =
+ typeof q.recommended === 'number' && Number.isInteger(q.recommended)
+ ? q.recommended
+ : undefined
+ let recommended: number | undefined
+ const options: AskQuestion['options'] = []
+ q.options.forEach((entry, i) => {
+ const o = entry as { label?: unknown; description?: unknown }
+ if (typeof o.label !== 'string') return
+ // Models trained on other harnesses mark a suggestion by suffixing the
+ // label; read it as the field so the answer carries the clean label.
+ const marked = RECOMMENDED_SUFFIX.exec(o.label)
+ const label = marked ? o.label.slice(0, marked.index) : o.label
+ // Blank options are dropped (checked after stripping, so a bare
+ // "(Recommended)" goes too).
+ if (!label.trim()) return
+ // Blanks shift the options after them, so the field's index is mapped
+ // to this option's position as it lands; the field wins over a suffix.
+ if (i === requested || (marked && requested === undefined)) {
+ recommended = options.length
+ }
+ options.push({
+ label,
...(typeof o.description === 'string'
? { description: o.description }
: {}),
- }))
+ })
+ })
if (options.length < 2) {
return `question '${q.id}' requires at least two labelled options`
}
+ // The answer names options by label, so two alike would be ambiguous.
+ if (new Set(options.map((o) => o.label)).size !== options.length) {
+ return `question '${q.id}' has duplicate option labels`
+ }
questions.push({
id: q.id,
question: q.question,
options,
...(q.multi === true ? { multi: true } : {}),
- ...(typeof q.recommended === 'number' && q.recommended >= 0
- ? { recommended: q.recommended }
- : {}),
+ ...(recommended !== undefined ? { recommended } : {}),
})
}
return { questions }
@@ -61,12 +88,48 @@ export function parseAskRequest(input: unknown): AskRequestPayload | string {
* card or the run was aborted; the model is told so plainly rather than being
* left to infer it from an empty array.
*/
+const NOT_ANSWERED =
+ 'The user did not answer. Proceed with your best judgement, and do not ask again unless something new depends on it.'
+
export function renderAskResult(answers: AskAnswer[] | null): ToolOutcome {
- if (answers === null) {
- return {
- output:
- 'The user did not answer. Proceed with your best judgement, and do not ask again unless something new depends on it.',
- }
- }
+ if (answers === null) return { output: NOT_ANSWERED }
return { output: JSON.stringify(answers) }
}
+
+/** One answered question as the transcript shows it; `answer` null = skipped. */
+export type AskSummaryRow = { question: string; answer: string | null }
+
+/**
+ * Pair a settled ask's questions with its answers for the transcript, so the
+ * user's choice stays visible after the card closes. Null when the part isn't
+ * one this can read (e.g. a malformed request that never showed a card).
+ */
+export function summarizeAsk(
+ input: unknown,
+ output: unknown
+): AskSummaryRow[] | null {
+ const request = parseAskRequest(input)
+ if (typeof request === 'string' || typeof output !== 'string') return null
+ if (output === NOT_ANSWERED) {
+ return request.questions.map((q) => ({
+ question: q.question,
+ answer: null,
+ }))
+ }
+ let answers: AskAnswer[]
+ try {
+ answers = JSON.parse(output)
+ } catch {
+ return null
+ }
+ if (!Array.isArray(answers)) return null
+ // Only a complete answer set is shown; a partial one would pass off the
+ // missing rows as skips the user never made.
+ const byId = new Map(answers.map((a) => [a?.id, a]))
+ if (request.questions.some((q) => !byId.has(q.id))) return null
+ return request.questions.map((q) => {
+ const a = byId.get(q.id)
+ const text = a?.custom_input?.trim() || a?.selected?.join(', ')
+ return { question: q.question, answer: text || null }
+ })
+}
diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.ts
index 373e40e0a..73beb0964 100644
--- a/web-app/src/lib/coworkTools.ts
+++ b/web-app/src/lib/coworkTools.ts
@@ -79,7 +79,7 @@ const todoTool: Tool = {
const askTool: Tool = {
description:
- 'Ask the user one or more structured questions. Use only when the answer materially changes the work.',
+ 'Ask the user one or more structured questions. Use only when the answer materially changes the work. To suggest an option, list it first and set `recommended` to its index rather than writing "(Recommended)" into the label.',
inputSchema: jsonSchema({
type: 'object',
properties: {
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 6e183e6da..79addddc3 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -784,10 +784,11 @@
"modelNoTools": "{{model}} can’t call tools, so it can’t act as an agent. Pick a tool-calling model.",
"askContinue": "Continue",
"askNext": "Next question",
+ "askPageOf": "{{current}} of {{total}}",
"askPrev": "Previous question",
+ "askSkipped": "Skipped",
"askRecommended": "Recommended",
"askSelectedCount": "{{count}} selected",
"askSomethingElse": "Something else",
- "askSomethingElsePlaceholder": "Type your own answer",
"submit": "Submit"
}
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 7c7dde267..119874de8 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -17,6 +17,7 @@ import {
import { toast } from 'sonner'
import { invoke } from '@tauri-apps/api/core'
import { Bot, Command, Sparkles } from 'lucide-react'
+import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import { cn } from '@/lib/utils'
import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'
import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'
@@ -1408,6 +1409,9 @@ function CoworkPage() {
}
}, [session?.id])
+ // With reduced motion the ask card only fades: no rise, no height fold.
+ const reduceMotion = useReducedMotion()
+
const respondAsk = useCallback(
(requestId: string, answers: AskAnswer[] | null) => {
if (session?.id) answerAsk(session.id, requestId, answers)
@@ -1632,15 +1636,35 @@ function CoworkPage() {
<div className="py-4 shrink-0">
<div className={cn('mx-auto w-full', !rail && 'md:w-4/5 xl:w-4/6')}>
- {ask && typeof ask.request !== 'string' && (
- <div className="px-1 pb-2">
- <CoworkAskCard
- requestId={ask.requestId}
- request={ask.request}
- onRespond={respondAsk}
- />
- </div>
- )}
+ {/* The card rises in when a question arrives and folds away once
+ answered, so the chat box glides instead of jumping. A card
+ already pending when the view mounts just appears. */}
+ <AnimatePresence initial={false}>
+ {ask && typeof ask.request !== 'string' && (
+ <motion.div
+ // A fresh card per request, so a new ask never renders a
+ // frame with the previous one's page or picks.
+ key={ask.requestId}
+ className="overflow-hidden px-1"
+ initial={
+ reduceMotion ? { opacity: 0 } : { opacity: 0, y: 8 }
+ }
+ animate={{ opacity: 1, y: 0, height: 'auto' }}
+ exit={
+ reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }
+ }
+ transition={{ duration: 0.2, ease: 'easeOut' }}
+ >
+ <div className="pb-2">
+ <CoworkAskCard
+ requestId={ask.requestId}
+ request={ask.request}
+ onRespond={respondAsk}
+ />
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
<div className="relative" onKeyDownCapture={onMenuKeyDown}>
{menuItems.length > 0 && (
<div className="absolute left-0 right-0 bottom-full mb-2 z-10 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-md">