Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(conversations): remove legacy harness state components and selectors

Steven Enamakeld4e0b90074ed
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 915e3beeed..8056a8a3d2 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -10,6 +10,7 @@ import { ComposerTriggerPopover } from '@/components/assistant-ui/composer-trigg
import { DirectiveText } from '@/components/assistant-ui/directive-text';
import { File } from '@/components/assistant-ui/file';
import { ThreadFollowupSuggestions } from '@/components/assistant-ui/follow-up-suggestions';
+import { ErrorState } from '@/components/assistant-ui/elements/error-state';
import { Image } from '@/components/assistant-ui/elements/image';
import { MessageTiming } from '@/components/assistant-ui/elements/message-timing.aui';
import { cn } from '@/components/assistant-ui/lib/utils';
@@ -33,7 +34,6 @@ import {
AuiIf,
BranchPickerPrimitive,
ComposerPrimitive,
- ErrorPrimitive,
type FileMessagePartComponent,
groupPartByType,
type ImageMessagePartComponent,
diff --git a/app/src/features/conversations/aui/ChatScheduleCard.tsx b/app/src/features/conversations/aui/ChatScheduleCard.tsx
index b5b2799ed3..9d1f2e3d72 100644
--- a/app/src/features/conversations/aui/ChatScheduleCard.tsx
+++ b/app/src/features/conversations/aui/ChatScheduleCard.tsx
@@ -13,6 +13,7 @@
* plus a best-effort toggle on top of it, not a substitute for the Settings
* panel's list.
*/
+import type { ToolCallMessagePartComponent } from '@assistant-ui/react';
import { useCallback, useState } from 'react';
import { ScheduleCard, type ScheduleRun } from '../../../components/assistant-ui/elements/schedule-card';
diff --git a/app/src/features/conversations/components/GoalBanner.test.tsx b/app/src/features/conversations/components/GoalBanner.test.tsx
deleted file mode 100644
index 8d0d944db9..0000000000
--- a/app/src/features/conversations/components/GoalBanner.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ThreadGoalView } from '../utils/harnessState';
-import { formatTokens, GoalBanner } from './GoalBanner';
-
-// Echo i18n keys so assertions read the stable key string; the interpolated
-// usage keys get their English templates so the substitution is visible.
-const TEMPLATES: Record<string, string> = {
- 'conversations.goal.tokens': '{used} tokens',
- 'conversations.goal.tokensWithBudget': '{used} / {budget} tokens',
-};
-vi.mock('../../../lib/i18n/I18nContext', () => ({
- useT: () => ({ t: (key: string) => TEMPLATES[key] ?? key }),
-}));
-
-function goal(partial: Partial<ThreadGoalView> = {}): ThreadGoalView {
- return {
- goalId: 'g1',
- objective: 'Ship the v2 release',
- status: 'active',
- tokensUsed: 1200,
- tokenBudget: 50000,
- ...partial,
- };
-}
-
-describe('GoalBanner', () => {
- it('renders the objective, status, and usage against the budget', () => {
- render(<GoalBanner goal={goal()} />);
- expect(screen.getByTestId('goal-objective').textContent).toBe('Ship the v2 release');
- expect(screen.getByTestId('goal-status').textContent).toBe('conversations.goal.status.active');
- expect(screen.getByTestId('goal-tokens').textContent).toBe('1.2k / 50k tokens');
- expect(screen.getByTestId('goal-banner').getAttribute('data-goal-status')).toBe('active');
- });
-
- it('drops the budget half when the goal has none', () => {
- render(<GoalBanner goal={goal({ tokenBudget: null, tokensUsed: 42 })} />);
- expect(screen.getByTestId('goal-tokens').textContent).toBe('42 tokens');
- });
-
- it.each([
- ['paused', 'conversations.goal.status.paused'],
- ['budget_limited', 'conversations.goal.status.budgetLimited'],
- ['complete', 'conversations.goal.status.complete'],
- ] as const)('labels the %s status', (status, key) => {
- render(<GoalBanner goal={goal({ status })} />);
- expect(screen.getByTestId('goal-status').textContent).toBe(key);
- expect(screen.getByTestId('goal-banner').getAttribute('data-goal-status')).toBe(status);
- });
-
- it('expands a clamped objective on click', () => {
- render(<GoalBanner goal={goal()} />);
- const objective = screen.getByTestId('goal-objective');
- expect(objective.getAttribute('aria-expanded')).toBe('false');
- fireEvent.click(objective);
- expect(objective.getAttribute('aria-expanded')).toBe('true');
- });
-});
-
-describe('formatTokens', () => {
- it('abbreviates thousands and millions, keeps small counts exact', () => {
- expect(formatTokens(0)).toBe('0');
- expect(formatTokens(999)).toBe('999');
- expect(formatTokens(1000)).toBe('1k');
- expect(formatTokens(1250)).toBe('1.3k');
- expect(formatTokens(50000)).toBe('50k');
- expect(formatTokens(2_500_000)).toBe('2.5M');
- });
-});
diff --git a/app/src/features/conversations/components/GoalBanner.tsx b/app/src/features/conversations/components/GoalBanner.tsx
deleted file mode 100644
index 5cff2885fa..0000000000
--- a/app/src/features/conversations/components/GoalBanner.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import React, { useState } from 'react';
-import { LuTarget } from 'react-icons/lu';
-
-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';
-import { cn } from '../../../lib/cn';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type { ThreadGoalStatus, ThreadGoalView } from '../utils/harnessState';
-
-/**
- * The thread's goal — the durable objective the agent set with `goal_set`
- * and keeps pursuing across turns — pinned above the composer as a
- * read-only strip: status pill, the objective, and token usage against the
- * budget when one was set. See {@link selectThreadGoal} for where it comes
- * from. A long objective clamps to one line and expands on click.
- */
-interface Props {
- goal: ThreadGoalView;
-}
-
-const STATUS_KEY: Record<ThreadGoalStatus, string> = {
- active: 'conversations.goal.status.active',
- paused: 'conversations.goal.status.paused',
- budget_limited: 'conversations.goal.status.budgetLimited',
- complete: 'conversations.goal.status.complete',
-};
-
-const STATUS_VARIANT: Record<ThreadGoalStatus, BadgeVariant> = {
- active: 'primary',
- paused: 'neutral',
- budget_limited: 'warning',
- complete: 'success',
-};
-
-/** `1234` → `1.2k`, `2500000` → `2.5M`; small counts stay exact. */
-export function formatTokens(count: number): string {
- if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
- if (count >= 1_000) return `${(count / 1_000).toFixed(1).replace(/\.0$/, '')}k`;
- return String(count);
-}
-
-export const GoalBanner: React.FC<Props> = ({ goal }) => {
- const { t } = useT();
- const [expanded, setExpanded] = useState(false);
- const usage =
- goal.tokenBudget !== null
- ? t('conversations.goal.tokensWithBudget')
- .replace('{used}', formatTokens(goal.tokensUsed))
- .replace('{budget}', formatTokens(goal.tokenBudget))
- : t('conversations.goal.tokens').replace('{used}', formatTokens(goal.tokensUsed));
-
- return (
- <section
- aria-label={t('conversations.goal.title')}
- data-testid="goal-banner"
- data-goal-status={goal.status}
- className={cn(
- 'mb-2 flex items-start gap-2 rounded-xl border bg-surface px-3 py-2 text-sm shadow-sm',
- goal.status === 'complete'
- ? 'border-sage-200 dark:border-sage-500/30'
- : 'border-primary-200 dark:border-primary-500/30'
- )}>
- <LuTarget
- aria-hidden
- className="mt-0.5 h-4 w-4 shrink-0 text-primary-700 dark:text-primary-200"
- />
- <div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-center gap-2">
- <span className="font-semibold text-content">{t('conversations.goal.title')}</span>
- <Badge variant={STATUS_VARIANT[goal.status]} data-testid="goal-status">
- {t(STATUS_KEY[goal.status])}
- </Badge>
- <span className="ml-auto text-xs text-content-secondary" data-testid="goal-tokens">
- {usage}
- </span>
- </div>
- <button
- type="button"
- data-analytics-id="goal-banner-toggle"
- aria-expanded={expanded}
- onClick={() => setExpanded(prev => !prev)}
- className={cn(
- 'mt-1 w-full text-left wrap-break-word text-content-secondary',
- !expanded && 'line-clamp-1'
- )}
- data-testid="goal-objective">
- {goal.objective}
- </button>
- </div>
- </section>
- );
-};
-
-export default GoalBanner;
diff --git a/app/src/features/conversations/components/PlanReviewCard.test.tsx b/app/src/features/conversations/components/PlanReviewCard.test.tsx
deleted file mode 100644
index 48a61dc84c..0000000000
--- a/app/src/features/conversations/components/PlanReviewCard.test.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { PendingPlanReview } from '../../../store/chatRuntimeSlice';
-import { PlanReviewCard } from './PlanReviewCard';
-
-// Echo i18n keys so we can assert on the stable key string.
-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));
-
-const mockCallCoreRpc = vi.fn();
-vi.mock('../../../services/coreRpcClient', () => ({
- callCoreRpc: (...args: unknown[]) => mockCallCoreRpc(...args),
-}));
-
-const mockDispatch = vi.fn();
-vi.mock('../../../store/hooks', () => ({ useAppDispatch: () => mockDispatch }));
-
-function review(partial: Partial<PendingPlanReview> = {}): PendingPlanReview {
- return {
- requestId: 'r1',
- summary: 'Ship the release',
- steps: ['step one', 'step two'],
- ...partial,
- };
-}
-
-describe('PlanReviewCard', () => {
- beforeEach(() => {
- mockCallCoreRpc.mockReset().mockResolvedValue({});
- mockDispatch.mockReset();
- });
-
- it('renders the summary and ordered steps', () => {
- render(<PlanReviewCard threadId="t1" review={review()} />);
- expect(screen.getByText('Ship the release')).toBeInTheDocument();
- expect(screen.getByText('step one')).toBeInTheDocument();
- expect(screen.getByText('step two')).toBeInTheDocument();
- });
-
- it('approves via plan_review_decide and clears optimistically', async () => {
- render(<PlanReviewCard threadId="t1" review={review()} />);
- fireEvent.click(screen.getByText('conversations.planReview.approve'));
- await waitFor(() =>
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.plan_review_decide',
- params: { request_id: 'r1', decision: 'approve', feedback: undefined },
- })
- );
- expect(mockDispatch).toHaveBeenCalledTimes(1);
- });
-
- it('rejects via plan_review_decide', async () => {
- render(<PlanReviewCard threadId="t1" review={review()} />);
- fireEvent.click(screen.getByText('conversations.planReview.reject'));
- await waitFor(() =>
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.plan_review_decide',
- params: { request_id: 'r1', decision: 'reject', feedback: undefined },
- })
- );
- });
-
- it('sends trimmed feedback as a revise decision; ignores blank input', async () => {
- render(<PlanReviewCard threadId="t1" review={review()} />);
- const send = screen.getByText('conversations.planReview.sendFeedback');
- const textarea = screen.getByTestId('plan-review-feedback') as HTMLTextAreaElement;
-
- // Blank → disabled, no call.
- fireEvent.click(send);
- expect(mockCallCoreRpc).not.toHaveBeenCalled();
-
- fireEvent.change(textarea, { target: { value: ' add a verification step ' } });
- fireEvent.click(send);
- await waitFor(() =>
- expect(mockCallCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.plan_review_decide',
- params: { request_id: 'r1', decision: 'revise', feedback: 'add a verification step' },
- })
- );
- });
-
- it('surfaces an error and stays mounted when the RPC fails', async () => {
- mockCallCoreRpc.mockRejectedValueOnce(new Error('boom'));
- render(<PlanReviewCard threadId="t1" review={review()} />);
- fireEvent.click(screen.getByText('conversations.planReview.approve'));
- await waitFor(() => expect(screen.getByText(/chat\.approval\.error/)).toBeInTheDocument());
- // Not cleared on failure.
- expect(mockDispatch).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/features/conversations/components/PlanReviewCard.tsx b/app/src/features/conversations/components/PlanReviewCard.tsx
deleted file mode 100644
index 688a7c2bd4..0000000000
--- a/app/src/features/conversations/components/PlanReviewCard.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import debug from 'debug';
-import React, { useState } from 'react';
-
-import Button from '../../../components/ui/Button';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { callCoreRpc } from '../../../services/coreRpcClient';
-import {
- clearPendingPlanReviewForThread,
- type PendingPlanReview,
-} from '../../../store/chatRuntimeSlice';
-import { useAppDispatch } from '../../../store/hooks';
-
-/**
- * Plan-mode review surface (Codex/Claude-style). The orchestrator parked the
- * live turn on a thread-scoped plan via the `request_plan_review` gate; this
- * card surfaces the plan above the composer and resolves the parked turn via
- * the `openhuman.plan_review_decide` RPC:
- *
- * - **Approve & run** → the turn resumes and executes the plan.
- * - **Reject** → the turn resumes and stops without executing.
- * - **Send feedback** → the turn resumes, re-plans from the free-text request,
- * and re-parks for another review.
- *
- * Mirrors {@link ApprovalRequestCard}: it owns the decision RPC and clears
- * itself optimistically; {@link ChatRuntimeProvider}'s turn-end handlers also
- * clear the pending review if the turn ends.
- */
-const log = debug('openhuman:chat:plan-review-card');
-
-type Decision = 'approve' | 'reject' | 'revise';
-
-interface Props {
- threadId: string;
- review: PendingPlanReview;
-}
-
-export const PlanReviewCard: React.FC<Props> = ({ threadId, review }) => {
- const { t } = useT();
- const dispatch = useAppDispatch();
- const [feedback, setFeedback] = useState('');
- const [deciding, setDeciding] = useState<Decision | null>(null);
- const [errorMsg, setErrorMsg] = useState<string | null>(null);
-
- const decide = async (decision: Decision, feedbackText?: string) => {
- if (deciding) return;
- setDeciding(decision);
- setErrorMsg(null);
- try {
- await callCoreRpc({
- method: 'openhuman.plan_review_decide',
- params: { request_id: review.requestId, decision, feedback: feedbackText },
- });
- // Resolve optimistically; ChatRuntimeProvider also clears on turn end.
- dispatch(clearPendingPlanReviewForThread({ threadId }));
- } catch (e) {
- log('plan_review_decide failed: %o', e);
- setErrorMsg(t('chat.approval.error'));
- setDeciding(null);
- }
- };
-
- const submitFeedback = () => {
- const trimmed = feedback.trim();
- if (!trimmed) return;
- void decide('revise', trimmed);
- };
-
- return (
- <div
- role="alertdialog"
- aria-label={t('conversations.planReview.title')}
- data-testid="plan-review-card"
- className="mb-2 rounded-xl border border-primary-300 bg-surface p-3 text-sm shadow-md dark:border-primary-700">
- <div className="flex items-start gap-2">
- <span aria-hidden className="text-base leading-none text-primary-700 dark:text-primary-200">
- 🗺️
- </span>
- <div className="min-w-0 flex-1">
- <p className="font-semibold text-primary-900 dark:text-primary-100">
- {t('conversations.planReview.title')}
- </p>
- <p className="mt-1 wrap-break-word text-primary-800/90 dark:text-primary-200/90">
- {review.summary?.trim() || t('conversations.planReview.subtitle')}
- </p>
-
- {review.steps.length > 0 && (
- <ol className="mt-2 max-h-56 list-decimal overflow-y-auto pl-6 text-content-secondary">
- {review.steps.map((step, i) => (
- <li key={i} className="wrap-break-word">
- {step}
- </li>
- ))}
- </ol>
- )}
-
- {errorMsg && (
- <p className="mt-2 text-xs text-coral-600 dark:text-coral-400">⚠ {errorMsg}</p>
- )}
-
- <div className="mt-3 flex flex-wrap items-center gap-2">
- <Button
- variant="primary"
- size="sm"
- data-analytics-id="plan-review-approve"
- onClick={() => void decide('approve')}
- disabled={deciding !== null}>
- {deciding === 'approve'
- ? t('chat.approval.deciding')
- : t('conversations.planReview.approve')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- data-analytics-id="plan-review-reject"
- onClick={() => void decide('reject')}
- disabled={deciding !== null}>
- {deciding === 'reject'
- ? t('chat.approval.deciding')
- : t('conversations.planReview.reject')}
- </Button>
- </div>
-
- <div className="mt-3">
- <label
- htmlFor="plan-review-feedback"
- className="mb-1 block text-xs font-medium text-primary-800/80 dark:text-primary-200/80">
- {t('conversations.planReview.feedbackLabel')}
- </label>
- <textarea
- id="plan-review-feedback"
- data-testid="plan-review-feedback"
- value={feedback}
- onChange={e => setFeedback(e.target.value)}
- onKeyDown={e => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
- e.preventDefault();
- submitFeedback();
- }
- }}
- rows={2}
- disabled={deciding !== null}
- placeholder={t('conversations.planReview.feedbackPlaceholder')}
- className="w-full resize-y rounded-lg border border-primary-200 bg-surface px-2.5 py-1.5 text-sm text-content shadow-inner outline-hidden focus:border-primary-400 disabled:opacity-50 dark:border-primary-800 dark:bg-surface-canvas"
- />
- <div className="mt-1.5 flex justify-end">
- <Button
- variant="secondary"
- size="sm"
- data-analytics-id="plan-review-send-feedback"
- onClick={submitFeedback}
- disabled={deciding !== null || feedback.trim().length === 0}>
- {deciding === 'revise'
- ? t('chat.approval.deciding')
- : t('conversations.planReview.sendFeedback')}
- </Button>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-};
diff --git a/app/src/features/conversations/components/TodoChecklist.test.tsx b/app/src/features/conversations/components/TodoChecklist.test.tsx
deleted file mode 100644
index 71254e254b..0000000000
--- a/app/src/features/conversations/components/TodoChecklist.test.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { TodoListView } from '../utils/harnessState';
-import { TodoChecklist } from './TodoChecklist';
-
-// Echo i18n keys so assertions read the stable key string; the one
-// interpolated key gets its English template so the count substitution is
-// visible.
-vi.mock('../../../lib/i18n/I18nContext', () => ({
- useT: () => ({
- t: (key: string) =>
- key === 'conversations.todos.progress' ? '{completed} of {total} done' : key,
- }),
-}));
-
-function list(partial: Partial<TodoListView> = {}): TodoListView {
- const items = partial.items ?? [
- { content: 'Read the spec', status: 'completed' as const },
- { content: 'Write the code', status: 'in_progress' as const },
- { content: 'Run the tests', status: 'pending' as const },
- ];
- const completed = items.filter(i => i.status === 'completed').length;
- return {
- items,
- completed,
- total: items.length,
- done: items.length > 0 && completed === items.length,
- ...partial,
- };
-}
-
-describe('TodoChecklist', () => {
- it('renders every item with its status marker in list order', () => {
- render(<TodoChecklist list={list()} />);
- const rows = screen.getAllByTestId('todo-item');
- expect(rows.map(r => r.textContent)).toEqual([
- 'Read the specconversations.todos.status.completed',
- 'Write the codeconversations.todos.status.inProgress',
- 'Run the testsconversations.todos.status.pending',
- ]);
- expect(rows.map(r => r.getAttribute('data-status'))).toEqual([
- 'completed',
- 'in_progress',
- 'pending',
- ]);
- });
-
- it('shows the completed count and exposes it as data attributes', () => {
- render(<TodoChecklist list={list()} />);
- expect(screen.getByTestId('todo-progress').textContent).toBe('1 of 3 done');
- const section = screen.getByTestId('todo-checklist');
- expect(section.getAttribute('data-todo-completed')).toBe('1');
- expect(section.getAttribute('data-todo-total')).toBe('3');
- expect(screen.getByTestId('todo-progress-bar').getAttribute('aria-valuenow')).toBe('33');
- });
-
- it('says all done once every item is completed', () => {
- render(
- <TodoChecklist
- list={list({
- items: [
- { content: 'a', status: 'completed' },
- { content: 'b', status: 'completed' },
- ],
- })}
- />
- );
- expect(screen.getByTestId('todo-progress').textContent).toBe('conversations.todos.allDone');
- expect(screen.getByTestId('todo-progress-bar').getAttribute('aria-valuenow')).toBe('100');
- });
-
- it('collapses to its header and expands again', () => {
- render(<TodoChecklist list={list()} />);
- const toggle = screen.getByRole('button', { expanded: true });
- fireEvent.click(toggle);
- expect(screen.queryByTestId('todo-items')).toBeNull();
- expect(screen.getByTestId('todo-progress')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { expanded: false }));
- expect(screen.getAllByTestId('todo-item')).toHaveLength(3);
- });
-});
diff --git a/app/src/features/conversations/components/TodoChecklist.tsx b/app/src/features/conversations/components/TodoChecklist.tsx
deleted file mode 100644
index 130dad88c6..0000000000
--- a/app/src/features/conversations/components/TodoChecklist.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import React, { useState } from 'react';
-import { LuCheck, LuChevronDown, LuChevronUp, LuListChecks } from 'react-icons/lu';
-
-import Progress from '../../../components/ui/Progress';
-import { cn } from '../../../lib/cn';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type { TodoItemStatus, TodoListView } from '../utils/harnessState';
-
-/**
- * The agent's todo list for this thread, pinned above the composer.
- *
- * Read-only progress: the agent owns the list (one whole-list `todo` write
- * per call), the pane just shows the latest write — see
- * {@link selectTodoList}. Exactly one item is `in_progress` at a time by the
- * store's invariant, so the pulse marks where the agent is; completed items
- * strike through and stay, so a five-step task reads as a checklist ticking
- * off rather than a list that shrinks. Collapses to its header so a long
- * list never crowds the composer.
- */
-interface Props {
- list: TodoListView;
-}
-
-const STATUS_LABEL_KEY: Record<TodoItemStatus, string> = {
- pending: 'conversations.todos.status.pending',
- in_progress: 'conversations.todos.status.inProgress',
- completed: 'conversations.todos.status.completed',
-};
-
-const Marker: React.FC<{ status: TodoItemStatus }> = ({ status }) => {
- if (status === 'completed') {
- return (
- <span
- aria-hidden
- className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-sage-500 text-content-inverted">
- <LuCheck className="h-3 w-3" strokeWidth={3} />
- </span>
- );
- }
- if (status === 'in_progress') {
- return (
- <span
- aria-hidden
- className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 border-primary-500">
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary-500" />
- </span>
- );
- }
- return (
- <span
- aria-hidden
- className="h-4 w-4 shrink-0 rounded-full border-2 border-line-strong dark:border-line-strong"
- />
- );
-};
-
-export const TodoChecklist: React.FC<Props> = ({ list }) => {
- const { t } = useT();
- const [collapsed, setCollapsed] = useState(false);
- const percent = list.total === 0 ? 0 : Math.round((list.completed / list.total) * 100);
- const progressLabel = t('conversations.todos.progress')
- .replace('{completed}', String(list.completed))
- .replace('{total}', String(list.total));
-
- return (
- <section
- aria-label={t('conversations.todos.title')}
- data-testid="todo-checklist"
- data-todo-completed={list.completed}
- data-todo-total={list.total}
- className={cn(
- 'mb-2 rounded-xl border bg-surface p-3 text-sm shadow-sm',
- list.done
- ? 'border-sage-200 dark:border-sage-500/30'
- : 'border-line dark:border-line-strong'
- )}>
- <button
- type="button"
- data-analytics-id="todo-checklist-toggle"
- aria-expanded={!collapsed}
- onClick={() => setCollapsed(prev => !prev)}
- className="flex w-full items-center gap-2 text-left">
- <LuListChecks
- aria-hidden
- className="h-4 w-4 shrink-0 text-primary-700 dark:text-primary-200"
- />
- <span className="font-semibold text-content">{t('conversations.todos.title')}</span>
- <span className="ml-auto text-xs text-content-secondary" data-testid="todo-progress">
- {list.done ? t('conversations.todos.allDone') : progressLabel}
- </span>
- {collapsed ? (
- <LuChevronDown aria-hidden className="h-4 w-4 shrink-0 text-content-faint" />
- ) : (
- <LuChevronUp aria-hidden className="h-4 w-4 shrink-0 text-content-faint" />
- )}
- </button>
-
- <Progress
- value={percent}
- aria-label={progressLabel}
- data-testid="todo-progress-bar"
- className="mt-2"
- />
-
- {!collapsed && (
- <ol className="mt-2 max-h-56 space-y-1.5 overflow-y-auto" data-testid="todo-items">
- {list.items.map((item, i) => (
- <li
- key={`${i}-${item.content}`}
- data-testid="todo-item"
- data-status={item.status}
- className="flex items-start gap-2">
- <span className="mt-0.5">
- <Marker status={item.status} />
- </span>
- <span
- className={cn(
- 'min-w-0 flex-1 wrap-break-word',
- item.status === 'completed' && 'text-content-faint line-through',
- item.status === 'in_progress' && 'font-medium text-content',
- item.status === 'pending' && 'text-content-secondary'
- )}>
- {item.content}
- </span>
- <span className="sr-only">{t(STATUS_LABEL_KEY[item.status])}</span>
- </li>
- ))}
- </ol>
- )}
- </section>
- );
-};
-
-export default TodoChecklist;
diff --git a/app/src/features/conversations/hooks/useThreadHarnessState.test.ts b/app/src/features/conversations/hooks/useThreadHarnessState.test.ts
deleted file mode 100644
index 8cfa9d3ec8..0000000000
--- a/app/src/features/conversations/hooks/useThreadHarnessState.test.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * useThreadHarnessState — unit tests.
- *
- * The hook's job is to put the thread's settled turns behind the live one and
- * read the todo list / goal out of both, so a reopened thread keeps a goal
- * that was set several turns ago. The history RPC is mocked; the selector
- * behaviour itself is covered in `utils/harnessState.test.ts`.
- */
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { useThreadHarnessState } from './useThreadHarnessState';
-
-const getTurnStateHistory = vi.hoisted(() => vi.fn());
-vi.mock('../../../services/api/threadApi', () => ({
- threadApi: { getTurnStateHistory: (...args: unknown[]) => getTurnStateHistory(...args) },
-}));
-
-/** A persisted tool row, as `threads_turn_state_history` returns it. */
-function persisted(name: string, output: unknown) {
- return {
- id: `${name}-persisted`,
- name,
- round: 1,
- status: 'success',
- output: JSON.stringify(output),
- };
-}
-
-/** A live tool row, as the socket stream builds it. */
-function live(name: string, result: unknown, seq: number): ToolTimelineEntry {
- return {
- id: `${name}-live`,
- name,
- round: 1,
- seq,
- status: 'success',
- result: JSON.stringify(result),
- };
-}
-
-const goalPayload = (status: string) => ({
- goal: {
- threadId: 't1',
- goalId: 'g1',
- objective: 'Ship the release',
- status,
- tokensUsed: 10,
- tokenBudget: 1000,
- },
- text: '',
-});
-
-const todoPayload = (statuses: string[]) => ({
- sessionId: 's1',
- todos: statuses.map((status, i) => ({ content: `step ${i + 1}`, status })),
- markdown: '',
-});
-
-const NO_LIVE_ROWS: ToolTimelineEntry[] = [];
-
-describe('useThreadHarnessState', () => {
- beforeEach(() => {
- getTurnStateHistory.mockReset().mockResolvedValue([]);
- });
-
- it('reads nothing for a thread with no history and no live rows', async () => {
- const { result } = renderHook(() => useThreadHarnessState('t1', NO_LIVE_ROWS));
- await waitFor(() => expect(getTurnStateHistory).toHaveBeenCalledWith('t1'));
- expect(result.current).toEqual({ todoList: null, goal: null });
- });
-
- it('never calls the history RPC without a thread', () => {
- const { result } = renderHook(() => useThreadHarnessState(null, NO_LIVE_ROWS));
- expect(getTurnStateHistory).not.toHaveBeenCalled();
- expect(result.current).toEqual({ todoList: null, goal: null });
- });
-
- it('restores a goal set in an earlier turn (history is newest-first)', async () => {
- getTurnStateHistory.mockResolvedValue([
- // Newest turn: only worked the list.
- { toolTimeline: [persisted('todo', todoPayload(['completed', 'in_progress']))] },
- // Older turn: where the goal was set.
- { toolTimeline: [persisted('goal_set', goalPayload('active'))] },
- ]);
-
- const { result } = renderHook(() => useThreadHarnessState('t1', NO_LIVE_ROWS));
- await waitFor(() => expect(result.current.goal?.goalId).toBe('g1'));
- expect(result.current.goal?.status).toBe('active');
- expect(result.current.todoList?.items.map(i => i.status)).toEqual(['completed', 'in_progress']);
- });
-
- it('lets the live turn win over the restored history', async () => {
- getTurnStateHistory.mockResolvedValue([
- { toolTimeline: [persisted('goal_set', goalPayload('active'))] },
- ]);
- const liveRows = [live('goal_complete', goalPayload('complete'), 1)];
-
- const { result } = renderHook(() => useThreadHarnessState('t1', liveRows));
- await waitFor(() => expect(result.current.goal?.status).toBe('complete'));
- });
-
- it('still shows the live turn when the history fetch fails', async () => {
- getTurnStateHistory.mockRejectedValue(new Error('rpc down'));
- const liveRows = [live('todo', todoPayload(['in_progress']), 1)];
-
- const { result } = renderHook(() => useThreadHarnessState('t1', liveRows));
- await waitFor(() => expect(getTurnStateHistory).toHaveBeenCalled());
- expect(result.current.todoList?.total).toBe(1);
- });
-
- it('refetches and drops the previous thread state on a thread switch', async () => {
- getTurnStateHistory.mockResolvedValue([
- { toolTimeline: [persisted('goal_set', goalPayload('active'))] },
- ]);
- const { result, rerender } = renderHook(
- ({ threadId }) => useThreadHarnessState(threadId, NO_LIVE_ROWS),
- { initialProps: { threadId: 't1' } }
- );
- await waitFor(() => expect(result.current.goal?.goalId).toBe('g1'));
-
- getTurnStateHistory.mockResolvedValue([]);
- rerender({ threadId: 't2' });
- await waitFor(() => expect(getTurnStateHistory).toHaveBeenCalledWith('t2'));
- await waitFor(() => expect(result.current.goal).toBeNull());
- });
-});
diff --git a/app/src/features/conversations/hooks/useThreadHarnessState.ts b/app/src/features/conversations/hooks/useThreadHarnessState.ts
deleted file mode 100644
index 950cf962f0..0000000000
--- a/app/src/features/conversations/hooks/useThreadHarnessState.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * The thread's harness work state — its todo list and its goal — for the
- * chat pane's checklist and goal banner.
- *
- * Both are written by agent tools and answered as JSON, so the newest `todo`
- * / `goal_*` tool result in the thread *is* the state; there is no RPC of
- * their own to read and no second store to keep in sync
- * ({@link selectTodoList} / {@link selectThreadGoal} do the reading).
- *
- * The live turn's rows come from Redux, which is all the pane needs while the
- * agent is working. The settled turns are fetched once per thread from
- * `threads_turn_state_history` — the same snapshots "View processing" replays
- * — because a goal is typically set in the turn the work *started* in: without
- * the earlier turns a reopened thread would show a checklist and no goal, or
- * neither, until the agent happened to touch them again.
- */
-import { useEffect, useMemo, useState } from 'react';
-
-import { threadApi } from '../../../services/api/threadApi';
-import { type ToolTimelineEntry, toolTimelineFromPersisted } from '../../../store/chatRuntimeSlice';
-import {
- selectThreadGoal,
- selectTodoList,
- type ThreadGoalView,
- type TodoListView,
-} from '../utils/harnessState';
-
-const EMPTY_TURNS: ToolTimelineEntry[][] = [];
-
-export interface ThreadHarnessState {
- todoList: TodoListView | null;
- goal: ThreadGoalView | null;
-}
-
-/**
- * Settled turns for `threadId`, oldest first. Empty until the fetch lands,
- * and on any failure: a missing history must never keep the live state off
- * the screen, and the live turn alone already covers the common case of an
- * agent working right now.
- */
-function useSettledTurns(threadId: string | null): ToolTimelineEntry[][] {
- const [turns, setTurns] = useState<ToolTimelineEntry[][]>(EMPTY_TURNS);
-
- useEffect(() => {
- if (!threadId) {
- setTurns(EMPTY_TURNS);
- return;
- }
- // Defensive for narrow test/embedder shims that expose only a subset of
- // threadApi; production builds always provide this method.
- if (typeof threadApi.getTurnStateHistory !== 'function') {
- setTurns(EMPTY_TURNS);
- return;
- }
- let cancelled = false;
- setTurns(EMPTY_TURNS);
- void (async () => {
- try {
- // History is newest-first; the pane scans newest-last, so reverse it.
- const history = await threadApi.getTurnStateHistory(threadId);
- if (cancelled) return;
- setTurns(
- history
- .slice()
- .reverse()
- .map(turn => (turn.toolTimeline ?? []).map(toolTimelineFromPersisted))
- );
- } catch {
- if (!cancelled) setTurns(EMPTY_TURNS);
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [threadId]);
-
- return turns;
-}
-
-/**
- * Reads the thread's todo list and goal out of `liveTimeline` (this turn) and
- * the thread's settled turns. The live turn goes last so anything the agent
- * writes right now wins over the persisted history it was restored from.
- */
-export function useThreadHarnessState(
- threadId: string | null,
- liveTimeline: ToolTimelineEntry[]
-): ThreadHarnessState {
- const settled = useSettledTurns(threadId);
- const turns = useMemo(() => [...settled, liveTimeline], [settled, liveTimeline]);
- return useMemo(
- () => ({ todoList: selectTodoList(turns), goal: selectThreadGoal(turns) }),
- [turns]
- );
-}
diff --git a/app/src/features/conversations/utils/harnessState.test.ts b/app/src/features/conversations/utils/harnessState.test.ts
deleted file mode 100644
index 70406a7b40..0000000000
--- a/app/src/features/conversations/utils/harnessState.test.ts
+++ /dev/null
@@ -1,213 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { selectThreadGoal, selectTodoList } from './harnessState';
-
-let nextSeq = 0;
-
-function entry(
- name: string,
- result: unknown,
- overrides: Partial<ToolTimelineEntry> = {}
-): ToolTimelineEntry {
- nextSeq += 1;
- return {
- id: `${name}-${nextSeq}`,
- name,
- round: 1,
- seq: nextSeq,
- status: 'success',
- result: typeof result === 'string' ? result : JSON.stringify(result),
- ...overrides,
- };
-}
-
-/** One turn's rows. The selectors take turns oldest-first. */
-const turn = (...entries: ToolTimelineEntry[]) => entries;
-
-const todoResult = (todos: Array<{ content: string; status?: string }>) => ({
- sessionId: 's1',
- todos,
- markdown: '',
-});
-
-const goalResult = (goal: Record<string, unknown> | null) => ({ goal, text: '' });
-
-describe('selectTodoList', () => {
- it('returns null when the agent never wrote a list', () => {
- expect(selectTodoList([])).toBeNull();
- expect(selectTodoList([turn(entry('file_read', 'contents'))])).toBeNull();
- });
-
- it('reads the newest successful todo write, by issue order not array order', () => {
- const first = entry(
- 'todo',
- todoResult([
- { content: 'Plan', status: 'in_progress' },
- { content: 'Build', status: 'pending' },
- ])
- );
- const second = entry(
- 'todo',
- todoResult([
- { content: 'Plan', status: 'completed' },
- { content: 'Build', status: 'in_progress' },
- ])
- );
- // Delivered out of order within the turn: the later write landed first in
- // the array, but its `seq` is higher.
- const list = selectTodoList([turn(second, first)]);
- expect(list).toEqual({
- items: [
- { content: 'Plan', status: 'completed' },
- { content: 'Build', status: 'in_progress' },
- ],
- completed: 1,
- total: 2,
- done: false,
- });
- });
-
- it('prefers the newest turn: a later turn supersedes an earlier list', () => {
- const earlier = turn(entry('todo', todoResult([{ content: 'Plan', status: 'in_progress' }])));
- const later = turn(entry('todo', todoResult([{ content: 'Plan', status: 'completed' }])));
- expect(selectTodoList([earlier, later])?.items[0].status).toBe('completed');
- });
-
- it('falls back to an earlier turn when the newest turn wrote no list', () => {
- const wrote = turn(entry('todo', todoResult([{ content: 'Plan', status: 'in_progress' }])));
- const quiet = turn(entry('file_read', 'contents'));
- expect(selectTodoList([wrote, quiet])?.items[0].content).toBe('Plan');
- });
-
- it('skips failed, running, and unparseable todo rows', () => {
- const good = entry('todo', todoResult([{ content: 'Only this', status: 'pending' }]));
- const failed = entry('todo', 'only one todo may be in_progress', { status: 'error' });
- const running = entry('todo', undefined, { status: 'running', result: undefined });
- const garbage = entry('todo', 'not json');
- const list = selectTodoList([turn(good, failed, running, garbage)]);
- expect(list?.items.map(i => i.content)).toEqual(['Only this']);
- });
-
- it('treats an empty write as a cleared list', () => {
- const wrote = entry('todo', todoResult([{ content: 'x', status: 'pending' }]));
- const cleared = entry('todo', todoResult([]));
- expect(selectTodoList([turn(wrote, cleared)])).toBeNull();
- });
-
- it('defaults an unknown status to pending and drops blank content', () => {
- const list = selectTodoList([
- turn(
- entry(
- 'todo',
- todoResult([
- { content: ' spaced ', status: 'blocked' },
- { content: ' ' },
- { content: 'done', status: 'completed' },
- ])
- )
- ),
- ]);
- expect(list).toEqual({
- items: [
- { content: 'spaced', status: 'pending' },
- { content: 'done', status: 'completed' },
- ],
- completed: 1,
- total: 2,
- done: false,
- });
- });
-
- it('reports done once every item is completed', () => {
- const list = selectTodoList([
- turn(
- entry(
- 'todo',
- todoResult([
- { content: 'a', status: 'completed' },
- { content: 'b', status: 'completed' },
- ])
- )
- ),
- ]);
- expect(list?.done).toBe(true);
- expect(list?.completed).toBe(2);
- });
-});
-
-describe('selectThreadGoal', () => {
- const active = {
- threadId: 't1',
- goalId: 'g1',
- objective: 'Ship the release',
- status: 'active',
- tokenBudget: 50000,
- tokensUsed: 1200,
- };
-
- it('returns null without a goal call', () => {
- expect(selectThreadGoal([])).toBeNull();
- expect(selectThreadGoal([turn(entry('todo', todoResult([])))])).toBeNull();
- });
-
- it('reads the goal a goal_set wrote', () => {
- expect(selectThreadGoal([turn(entry('goal_set', goalResult(active)))])).toEqual({
- goalId: 'g1',
- objective: 'Ship the release',
- status: 'active',
- tokensUsed: 1200,
- tokenBudget: 50000,
- });
- });
-
- // The reason the selectors scan every turn: a goal is set in the turn the
- // work starts in and then goes untouched for turns on end.
- it('keeps a goal set several turns ago', () => {
- const set = turn(entry('goal_set', goalResult(active)));
- const working = turn(entry('todo', todoResult([{ content: 'Plan', status: 'in_progress' }])));
- const stillWorking = turn(entry('file_read', 'contents'));
- expect(selectThreadGoal([set, working, stillWorking])?.goalId).toBe('g1');
- });
-
- it('follows the newest call: goal_complete supersedes goal_set', () => {
- const set = turn(entry('goal_set', goalResult(active)));
- const done = turn(entry('goal_complete', goalResult({ ...active, status: 'complete' })));
- expect(selectThreadGoal([set, done])?.status).toBe('complete');
- });
-
- it('clears the banner when goal_get reports no goal', () => {
- const set = turn(entry('goal_set', goalResult(active)));
- const absent = turn(entry('goal_get', goalResult(null)));
- expect(selectThreadGoal([set, absent])).toBeNull();
- });
-
- it('ignores errored calls and payloads without a goal field', () => {
- const set = entry('goal_set', goalResult(active));
- const failed = entry('goal_set', 'Missing objective', { status: 'error' });
- const other = entry('goal_get', { text: 'legacy text-only shape' });
- expect(selectThreadGoal([turn(set, failed, other)])?.goalId).toBe('g1');
- });
-
- // `goal_set` / `goal_get` sit in the `goals` tool pack, so the model calls
- // them through `use_skill` and the row is named for the wrapper.
- it('reads a goal call made through the use_skill wrapper', () => {
- expect(selectThreadGoal([turn(entry('use_skill', goalResult(active)))])?.goalId).toBe('g1');
- });
-
- it('ignores an unrelated use_skill result', () => {
- const set = entry('goal_set', goalResult(active));
- const unrelated = entry('use_skill', { ok: true, goal: 'a bare string, not a goal' });
- expect(selectThreadGoal([turn(set, unrelated)])?.goalId).toBe('g1');
- });
-
- it('treats a missing budget as unbounded', () => {
- const goal = selectThreadGoal([
- turn(
- entry('goal_set', goalResult({ ...active, tokenBudget: undefined, tokensUsed: undefined }))
- ),
- ]);
- expect(goal?.tokenBudget).toBeNull();
- expect(goal?.tokensUsed).toBe(0);
- });
-});
diff --git a/app/src/features/conversations/utils/harnessState.ts b/app/src/features/conversations/utils/harnessState.ts
deleted file mode 100644
index 250a2e87f9..0000000000
--- a/app/src/features/conversations/utils/harnessState.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * Harness-level work state derived from a thread's tool timeline.
- *
- * The agent keeps two pieces of state while it works on a long request: a
- * **todo list** (the `todo` tool — one whole-list write per call, Claude
- * Code / Codex style) and a **thread goal** (`goal_set` / `goal_get` /
- * `goal_complete` — the durable objective for the thread). Neither has an
- * RPC of its own; the core answers each tool call with a JSON payload, and
- * that payload rides the tool result into the timeline (`ToolTimelineEntry.
- * result`) both live and on reload. So the pane shows what the agent last
- * wrote by reading the newest successful call of each kind — the same
- * mechanism the transcript uses, with no second source of truth to drift.
- *
- * Both selectors take the thread's turns oldest-first — the settled turns
- * restored from `threads_turn_state_history` followed by the live one — and
- * scan backwards, because the state the pane shows is whatever the agent
- * wrote last. Scanning turns (rather than one flat array) is what makes a
- * reloaded thread keep its goal: `goal_set` usually lands in the turn the
- * work started in, several turns before the one the pane is rendering.
- *
- * Both are pure, so the checklist and banner can be tested without a store.
- */
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-
-export type TodoItemStatus = 'pending' | 'in_progress' | 'completed';
-
-export interface TodoItemView {
- content: string;
- status: TodoItemStatus;
-}
-
-export interface TodoListView {
- items: TodoItemView[];
- /** Items marked `completed`. */
- completed: number;
- total: number;
- /** Whether every item is completed (and there is at least one). */
- done: boolean;
-}
-
-export type ThreadGoalStatus = 'active' | 'paused' | 'budget_limited' | 'complete';
-
-export interface ThreadGoalView {
- goalId: string;
- objective: string;
- status: ThreadGoalStatus;
- tokensUsed: number;
- tokenBudget: number | null;
-}
-
-const TODO_TOOL = 'todo';
-/**
- * `goal_complete` is a direct tool; `goal_set` / `goal_get` live in the
- * `goals` tool pack, so the model reaches them through `use_skill` and the
- * timeline row is named for the wrapper, not the goal tool. Matching the
- * wrapper is safe because the payload check below is exact — a `use_skill`
- * result only counts when it carries a `goal` key of the right shape.
- */
-const GOAL_TOOLS = new Set(['goal_set', 'goal_get', 'goal_complete', 'use_skill']);
-const TODO_STATUSES: ReadonlySet<string> = new Set(['pending', 'in_progress', 'completed']);
-const GOAL_STATUSES: ReadonlySet<string> = new Set([
- 'active',
- 'paused',
- 'budget_limited',
- 'complete',
-]);
-
-function parseResult(entry: ToolTimelineEntry): Record<string, unknown> | null {
- if (entry.status !== 'success' || !entry.result) return null;
- try {
- const parsed: unknown = JSON.parse(entry.result);
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
- ? (parsed as Record<string, unknown>)
- : null;
- } catch {
- return null;
- }
-}
-
-/**
- * Newest-first walk of every turn's rows: turns in reverse order, and within
- * a turn by issue order (`seq`) rather than array order — a
- * `tool_args_delta` for a later parallel call can land ahead of an earlier
- * one, and the last write is the one that counts. `seq` is per-turn, which is
- * exactly why the turns are walked separately instead of being flattened.
- */
-function newestFirst(turns: ToolTimelineEntry[][]): ToolTimelineEntry[] {
- const out: ToolTimelineEntry[] = [];
- for (let i = turns.length - 1; i >= 0; i -= 1) {
- out.push(...[...turns[i]].sort((a, b) => b.seq - a.seq));
- }
- return out;
-}
-
-function parseTodoItems(raw: unknown): TodoItemView[] | null {
- if (!Array.isArray(raw)) return null;
- const items: TodoItemView[] = [];
- for (const candidate of raw) {
- if (!candidate || typeof candidate !== 'object') continue;
- const { content, status } = candidate as { content?: unknown; status?: unknown };
- if (typeof content !== 'string' || !content.trim()) continue;
- items.push({
- content: content.trim(),
- status:
- typeof status === 'string' && TODO_STATUSES.has(status)
- ? (status as TodoItemStatus)
- : 'pending',
- });
- }
- return items;
-}
-
-/**
- * The list the agent last wrote in this thread, or `null` when it has not
- * written one (or cleared it). `turns` is oldest-first. A sub-agent's own `todo` calls live inside its
- * parent row's `subagent.toolCalls`, never at the top level, so only the
- * thread's own agent reaches this.
- */
-export function selectTodoList(turns: ToolTimelineEntry[][]): TodoListView | null {
- for (const entry of newestFirst(turns)) {
- if (entry.name !== TODO_TOOL) continue;
- const payload = parseResult(entry);
- if (!payload) continue;
- const items = parseTodoItems(payload.todos);
- if (!items) continue;
- if (items.length === 0) return null;
- const completed = items.filter(item => item.status === 'completed').length;
- return { items, completed, total: items.length, done: completed === items.length };
- }
- return null;
-}
-
-/**
- * The thread goal as of the agent's last goal call (`turns` oldest-first):
- * `goal_set` and
- * `goal_complete` carry the goal they wrote, `goal_get` the one it read (or
- * `null` when the thread has none, which clears the banner).
- */
-export function selectThreadGoal(turns: ToolTimelineEntry[][]): ThreadGoalView | null {
- for (const entry of newestFirst(turns)) {
- if (!GOAL_TOOLS.has(entry.name)) continue;
- const payload = parseResult(entry);
- if (!payload || !('goal' in payload)) continue;
- const goal = payload.goal;
- if (goal === null) return null;
- if (!goal || typeof goal !== 'object') continue;
- const { goalId, objective, status, tokensUsed, tokenBudget } = goal as Record<string, unknown>;
- if (typeof objective !== 'string' || typeof status !== 'string' || !GOAL_STATUSES.has(status))
- continue;
- return {
- goalId: typeof goalId === 'string' ? goalId : '',
- objective,
- status: status as ThreadGoalStatus,
- tokensUsed: typeof tokensUsed === 'number' ? tokensUsed : 0,
- tokenBudget: typeof tokenBudget === 'number' ? tokenBudget : null,
- };
- }
- return null;
-}
diff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rs
index b74a7f8bdc..0211c43a2b 100644
--- a/crates/openhuman-core/src/config/schema/types/config.rs
+++ b/crates/openhuman-core/src/config/schema/types/config.rs
@@ -154,6 +154,11 @@ pub struct Config {
#[serde(default)]
pub shell: ShellConfig,
+ /// `[web_chat]` — web chat presentation-layer toggles (currently just
+ /// the post-turn follow-up-suggestions model call).
+ #[serde(default)]
+ pub web_chat: crate::config::schema::WebChatConfig,
+
#[serde(default)]
pub reliability: ReliabilityConfig,