Skip to content

Show user corrective messages in the goal execution timeline (readable log and raw terminal view) #2467

Closed

Description

@propr-dev

Context

While a goal is running, the operator can steer the coding agent from the Steering console on the goal detail page (/goals/:goalId). There are three ways to do this today:

  1. The free-text Correction or follow-up textarea (sendGoalInput(goal.id, { message })).
  2. The canned Quick actions buttons — What's done? / What's left? (sendGoalInput(goal.id, { canned })).
  3. Attachments sent alongside either of the above.

All of these are persisted durably in the goal_inputs table (packages/core/src/db/migrations/20260902010000_harden_native_goals.js) and are delivered to the provider either live (Codex / Claude native goal control plane) or at the next provider turn boundary (whole-session providers such as Antigravity).

The problem: the agent receives and acts on those messages, but the operator has no evidence of that in the UI. The Goal output panel in propr-ui/src/pages/GoalsPage.tsx is built entirely from useTaskLiveData(goal.taskId), which projects the provider's own stdout stream (ConversationEvent[]). ProPR-side control-plane messages never appear in that stream, so the timeline reads as if the agent spontaneously changed direction. Users cannot answer "did my correction land, and when?".

This issue adds user messages to the same timeline, in chronological order, in both the Human readable view (ThinkingLog) and the Raw terminal view (ExecutionEventLog).

Requirements

  1. Backend projection. serializeGoal must expose the goal's user-originated inputs so the detail page can render them. Only operator-authored messages are included:
    • Include kind = 'input' rows (free-text corrections and canned status requests).
    • Exclude kind = 'context' (ProPR's own delivery-policy message), kind = 'resume' (the synthetic GOAL_CONTINUE_INPUT nudge) and kind = 'control' (pause/cancel/model bookkeeping rows with an empty message).
  2. No internal path leakage. addGoalInput stores the message after appendGoalAttachments has appended a block containing absolute storedPath values under /tmp/git-processor/goal-attachments/.... The projection must strip that appended block and instead report a bounded attachmentCount.
  3. Bounded payload. Cap the projected list (newest 200 rows) and truncate each message body (4,000 characters, with a truncated flag). The goal list endpoint must not pay for this — only single-goal responses carry inputs.
  4. Delivery state is visible. Each projected input carries state (pending / delivered / undeliverable), createdAt and deliveredAt, so the UI can distinguish "queued for the next provider boundary" from "already delivered".
  5. Chronological merge in the UI. User messages are interleaved with provider events by time, using deliveredAt ?? createdAt. Still-pending messages always render at the end of the timeline (they have not reached the provider yet) with a Queued badge.
  6. Both views. The merged timeline is used for the Human readable view (ThinkingLog) and the Raw terminal view (ExecutionEventLog), so switching views never loses the user's own messages.
  7. Visually distinct. User messages must be immediately distinguishable from agent output — a distinct gutter label (YOU), a distinct icon, and a distinct accent colour.
  8. No regressions for tasks. The shared TaskDetails components are also used by the task detail page, which never produces user_input events. All new branches must be additive and fall through harmlessly.

Implementation Specification

Backend

  1. packages/api/services/goalAttachmentService.ts
    • Export the constant used by appendGoalAttachments to introduce its appended block (extract it if it is currently inline), e.g. GOAL_ATTACHMENT_SECTION_HEADING.
    • Add and export stripGoalAttachmentSection(message: string): { message: string; attachmentCount: number }.
  2. packages/api/services/goalProjection.ts
    • Add GoalInputProjection and loadGoalInputs().
    • Add an options parameter to serializeGoal ({ includeInputs?: boolean }, default true) and include inputs in the returned projection. redactVisualPreviewValue already runs over the whole projection, so preview paths stay redacted.
  3. packages/api/routes/goalRoutes.ts
    • Pass { includeInputs: false } from the list handler only. Every single-goal handler (get, pause, resume, cancel, requestModel, input) keeps the default so the detail page never loses messages after a control action.

Frontend

  1. propr-ui/src/api/goals.ts — add the GoalInput type and inputs: GoalInput[] on Goal.
  2. propr-ui/src/components/TaskDetails/types.ts — widen LiveEvent['type'] with 'user_input' and add the optional inputState / attachmentCount / truncated fields.
  3. propr-ui/src/components/Goals/goalTimeline.ts (new) — pure merge helper mergeGoalTimeline(events, inputs, options).
  4. propr-ui/src/components/TaskDetails/ExecutionEventUtils.ts — handle user_input in getCategoryDisplay and extractEventSummary.
  5. propr-ui/src/components/TaskDetails/ExecutionEventHelpers.tsx — handle user_input in EventIcon.
  6. propr-ui/src/components/TaskDetails/ExecutionEventLog.tsx — render expanded user-message content.
  7. propr-ui/src/components/TaskDetails/ThinkingLog.tsx — render a distinct user-message row.
  8. propr-ui/src/pages/GoalsPage.tsx — merge goal.inputs into both views.

Tests

  1. propr-ui/src/components/Goals/goalTimeline.test.ts (new) — ordering, pending-at-end, unparsable timestamps.
  2. packages/api/test/goalProjection.test.ts — projection filters kinds, strips attachment paths, bounds size, and includeInputs: false omits the field.
  3. propr-ui/src/pages/GoalsPage.test.tsx — the detail view renders a delivered correction inside the implementation log and a pending correction with a Queued badge.

Acceptance Criteria

  • Sending a correction from the Steering console makes that exact text appear in the Human readable goal output within one poll cycle (≤ 5s), labelled YOU.
  • The same message appears in the Raw terminal view when the user toggles to it.
  • A message that has not yet been delivered renders at the end of the timeline with a Queued badge; once delivered_at is set it is re-ordered into its chronological position.
  • Canned What's done? / What's left? messages appear in the timeline.
  • ProPR's own context, resume and control rows never appear in the timeline.
  • No /tmp/git-processor/goal-attachments/... path is visible anywhere in the timeline; a message sent with two files shows an attachment count of 2 instead.
  • GET /api/goals (list) response contains no inputs field; GET /api/goals/:id does.
  • The task detail page (/tasks/:taskId) is unchanged — no user_input events exist there and no rendering branch is taken.
  • npm --workspace propr-ui test -- src/pages/GoalsPage.test.tsx src/components/Goals/goalTimeline.test.ts passes.
  • node scripts/run-test-suite.mjs packages/api/test/goalProjection.test.ts passes.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 22, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    User corrective messages already exist as durable rows in goal_inputs; they are not part of the provider's stdout stream. That is the key architectural fact driving this design.

    Why project from the database rather than inject into the live stream. The obvious alternative is to write a synthetic envelope into the Redis live-output stream (agent:output:<taskId>) whenever a control message is delivered, so it flows through the existing parsers. That was rejected for three reasons: (1) it would corrupt a stream whose contract is "verbatim provider output", which several parsers (detectStoredOutputFormat, parseAgentStreamOutput, the Codex/OpenCode/Antigravity adapters) sniff by shape; (2) the stream is rebuilt on every poll, so a message queued but not yet delivered would have nowhere to live; and (3) the durable rows already carry richer state (pending / delivered / undeliverable, created_at, delivered_at) that the UI needs in order to answer "did my correction land?". Projecting from the database keeps the provider stream pure and makes the feature correct across worker restarts and whole-session resumes.

    Why merge in the UI rather than server-side. The provider stream is parsed and paginated by useTaskLiveData; merging server-side would require the API to own event ordering for a stream it does not otherwise materialize. Merging client-side keeps the change to one small pure function that both views share, and keeps the merge testable without Redis.

    Timestamp-drift trade-off. parseAgentStreamOutput synthesizes monotonic timestamps for providers whose envelopes carry none (executionStartTimestamp + index * 1000). Over a long goal those synthetic stamps can drift from wall clock, so a merged user message may land slightly off its true position. This is accepted because it is bounded and cosmetic; pending messages are pinned to the end of the list so the one case where correctness matters ("has this been delivered yet?") is never ambiguous.

    Why widen LiveEvent instead of introducing a parallel list. A second render path would double the styling, collapse/expand and gutter logic in two components. Widening the union keeps exactly one timeline renderer; every new branch is additive and falls through for task pages, which never emit user_input.


    File: packages/api/services/goalAttachmentService.ts

    Why this file: addGoalInput persists the message after appendGoalAttachments has appended a block containing absolute storedPath values. Since the projection added below returns those messages to the browser, the stripping helper must live next to the appender so both sides share one definition of the block's boundary and can never drift.

    Extract the heading that appendGoalAttachments already emits into an exported constant, then add the inverse operation:

    // Single source of truth for the attachment block boundary. `appendGoalAttachments`
    // writes it and `stripGoalAttachmentSection` removes it; keeping one constant means
    // the append/strip pair can never drift out of sync as the block format evolves.
    export const GOAL_ATTACHMENT_SECTION_HEADING = '\n\nAttached files:';
    
    /**
     * Remove the ProPR-appended attachment block from a stored goal input.
     *
     * The persisted message intentionally contains absolute container paths under
     * /tmp/git-processor/goal-attachments so the agent can open the files. Those paths
     * are internal runtime detail and must never reach the browser, so anything the
     * API projects back to a client goes through here first. We return a count rather
     * than the filenames because the count is all the timeline needs, and a count
     * cannot leak a path no matter how the block format changes.
     */
    export function stripGoalAttachmentSection(
      message: string,
    ): { message: string; attachmentCount: number } {
      const index = message.indexOf(GOAL_ATTACHMENT_SECTION_HEADING);
      if (index === -1) return { message, attachmentCount: 0 };
      const section = message.slice(index + GOAL_ATTACHMENT_SECTION_HEADING.length);
      // Each appended attachment occupies exactly one line, so counting non-empty
      // lines is a stable count that does not depend on the per-line format.
      const attachmentCount = section.split('\n').filter(line => line.trim().length > 0).length;
      return { message: message.slice(0, index).trimEnd(), attachmentCount };
    }

    Then update appendGoalAttachments to build its block from GOAL_ATTACHMENT_SECTION_HEADING instead of an inline literal, so the two stay coupled.


    File: packages/api/services/goalProjection.ts

    Why this file: this is the single boundary where a goals row becomes the JSON the goal detail page consumes. Adding inputs here means every handler that already returns a serialized goal (get, pause, resume, cancel, requestModel, input) automatically carries the messages, so a control action cannot momentarily blank the timeline. It is also already wrapped in redactVisualPreviewValue, so the new field inherits preview-path redaction for free.

    --- a/packages/api/services/goalProjection.ts
    +++ b/packages/api/services/goalProjection.ts
    @@
     import { projectTaskLiveDetails } from '../routes/liveDetailsRoutes.js';
    -import { parseGoalAttachments, publicGoalAttachments } from './goalAttachmentService.js';
    +import {
    +  parseGoalAttachments,
    +  publicGoalAttachments,
    +  stripGoalAttachmentSection,
    +} from './goalAttachmentService.js';
    +
    +/** Newest-first cap. A goal can accumulate unbounded corrections; the timeline
    + *  only needs recent history, and an unbounded array would grow every poll. */
    +const MAX_PROJECTED_GOAL_INPUTS = 200;
    +/** Inputs accept up to 65,536 characters. Truncate for transport and flag it so
    + *  the UI can say "truncated" instead of silently showing a partial message. */
    +const MAX_PROJECTED_GOAL_INPUT_CHARACTERS = 4_000;
    +
    +export interface GoalInputProjection {
    +  id: string;
    +  message: string;
    +  /** 'pending' means the provider has not received it yet; the UI pins these last. */
    +  state: 'pending' | 'delivered' | 'undeliverable';
    +  createdAt: string;
    +  deliveredAt: string | null;
    +  attachmentCount: number;
    +  truncated: boolean;
    +}
    +
    +/**
    + * Project operator-authored goal inputs for the execution timeline.
    + *
    + * Only `kind = 'input'` rows are returned. The other kinds are ProPR's own
    + * control plane, not user speech, and showing them would make the timeline read
    + * as if the operator said things they never typed:
    + *   - 'context' is the launch-policy message ProPR composes itself
    + *   - 'resume'  is the synthetic GOAL_CONTINUE_INPUT nudge after a boundary
    + *   - 'control' rows exist purely for idempotency and carry an empty message
    + */
    +async function loadGoalInputs(db: Knex, row: GoalProjectionRow): Promise<GoalInputProjection[]> {
    +  const rows = await db('goal_inputs')
    +    .where({ goal_id: row.goal_id, owner_id: row.owner_id, kind: 'input' })
    +    .orderBy('sequence', 'desc')
    +    .limit(MAX_PROJECTED_GOAL_INPUTS)
    +    .select('input_id', 'message', 'state', 'created_at', 'delivered_at');
    +
    +  // Re-sort ascending: the DESC + LIMIT above selects the newest window, but the
    +  // timeline consumes oldest-first.
    +  return rows.reverse().map(input => {
    +    // Strip before truncating so an attachment block can never survive as a
    +    // partial path fragment at the truncation boundary.
    +    const { message, attachmentCount } = stripGoalAttachmentSection(String(input.message ?? ''));
    +    const truncated = message.length > MAX_PROJECTED_GOAL_INPUT_CHARACTERS;
    +    return {
    +      id: String(input.input_id),
    +      message: truncated ? message.slice(0, MAX_PROJECTED_GOAL_INPUT_CHARACTERS) : message,
    +      state: input.state === 'pending' || input.state === 'undeliverable' ? input.state : 'delivered',
    +      createdAt: String(input.created_at),
    +      deliveredAt: input.delivered_at ? String(input.delivered_at) : null,
    +      attachmentCount,
    +      truncated,
    +    } satisfies GoalInputProjection;
    +  });
    +}
     
     export async function serializeGoal(
       db: Knex,
       redis: RedisClientType,
       source: GoalProjectionRow,
    +  // Defaults to true so every single-goal handler (get/pause/resume/cancel/model/input)
    +  // carries the timeline without each call site having to remember to opt in. The
    +  // list endpoint, which serializes up to 200 goals, opts out explicitly.
    +  options: { includeInputs?: boolean } = {},
     ) {
       const row = source;
       const live = await projectTaskLiveDetails(redis, db, row.current_task_id, { sessionId: row.session_id });
    @@
       const timing = goalTiming(row);
    +  const inputs = options.includeInputs === false ? [] : await loadGoalInputs(db, row);
       const projection = {
    @@
         attachments: publicGoalAttachments(parseGoalAttachments(row.attachments)),
    +    inputs,
         baseBranch: row.base_branch,

    File: packages/api/routes/goalRoutes.ts

    Why this file: the list endpoint serializes up to 200 goals per request. Running one extra goal_inputs query per goal there would add 200 round trips for data the list view never renders, so the list is the one place that opts out.

    --- a/packages/api/routes/goalRoutes.ts
    +++ b/packages/api/routes/goalRoutes.ts
    @@
         const goals = await timeApiStage('goals.projection', () =>
    -      Promise.all(rows.map(row => serializeGoal(deps.db, deps.redisClient, row)))
    +      // The queue rows render title/objective/status only, so skip the per-goal
    +      // goal_inputs query that would otherwise run once per listed goal.
    +      Promise.all(rows.map(row => serializeGoal(deps.db, deps.redisClient, row, { includeInputs: false })))
         );

    Leave every other serializeGoal(...) call in this file untouched — they are all single-goal responses consumed by the detail page and must keep the default includeInputs: true.


    File: propr-ui/src/api/goals.ts

    Why this file: this is the typed contract the goal detail page reads. Adding GoalInput here is what lets GoalsPage and the merge helper stay type-safe without any.

    --- a/propr-ui/src/api/goals.ts
    +++ b/propr-ui/src/api/goals.ts
    @@
     export interface GoalAttachment {
       id: string;
       originalName: string;
       mimeType: string;
       size: number;
       tokenEstimate: number;
       type: 'image' | 'text';
     }
     
    +/** One operator-authored steering message, projected for the execution timeline.
    + *  `state` is what lets the UI distinguish "already delivered to the provider"
    + *  from "queued for the next provider turn boundary". */
    +export interface GoalInput {
    +  id: string;
    +  message: string;
    +  state: 'pending' | 'delivered' | 'undeliverable';
    +  createdAt: string;
    +  deliveredAt: string | null;
    +  attachmentCount: number;
    +  truncated: boolean;
    +}
    +
     export type GoalVisualPreview = PublishedVisualPreview;
    @@
       initialPrompt: string;
       attachments: GoalAttachment[];
    +  /** Absent on the list endpoint, which opts out of the projection for cost. */
    +  inputs?: GoalInput[];
       baseBranch: string | null;

    File: propr-ui/src/components/TaskDetails/types.ts

    Why this file: LiveEvent is the shared shape rendered by both ThinkingLog and ExecutionEventLog. Widening the union here is what allows one renderer to handle both agent output and user messages, instead of duplicating the timeline in a second component.

    Locate the LiveEvent interface and widen its type union plus add the user-message fields:

    --- a/propr-ui/src/components/TaskDetails/types.ts
    +++ b/propr-ui/src/components/TaskDetails/types.ts
    @@
     export interface LiveEvent {
       id?: string;
    -  type: 'thought' | 'tool_use' | 'tool_result';
    +  // 'user_input' is synthesized client-side by mergeGoalTimeline; no backend
    +  // parser produces it, so task pages never take the new render branches.
    +  type: 'thought' | 'tool_use' | 'tool_result' | 'user_input';
       content?: string;
    +  /** user_input only: delivery state, so the UI can badge queued messages. */
    +  inputState?: 'pending' | 'delivered' | 'undeliverable';
    +  /** user_input only: how many files were attached to this message. */
    +  attachmentCount?: number;
    +  /** user_input only: the projected body was clipped for transport. */
    +  truncated?: boolean;
       toolName?: string;

    File: propr-ui/src/components/Goals/goalTimeline.ts (new file)

    Why this file: a single pure function owns the ordering rule, so the readable view and the terminal view can never diverge, and the rule is unit-testable without Redis, sockets or a rendered page.

    import type { GoalInput } from '../../api/goals';
    import type { LiveEvent } from '../TaskDetails/types';
    
    interface MergeOptions {
      /** Optional formatter so the readable view can show "6m 59s" beside a user
       *  message, exactly like agent thoughts. Kept as a callback so this module
       *  never imports UI formatting helpers and stays trivially testable. */
      formatRelativeTime?: (timestamp: string) => string | null;
    }
    
    type TimelineEvent = LiveEvent & { relativeTime?: string | null };
    
    /** Delivered messages are anchored to when the provider actually received them;
     *  that is the position where the agent's behaviour changes. Only fall back to
     *  createdAt when delivery has not been recorded. */
    const anchorTimestamp = (input: GoalInput): string => input.deliveredAt ?? input.createdAt;
    
    function toTimelineEvent(input: GoalInput, options: MergeOptions): TimelineEvent {
      const timestamp = anchorTimestamp(input);
      return {
        id: `goal-input-${input.id}`,
        type: 'user_input',
        content: input.message,
        inputState: input.state,
        attachmentCount: input.attachmentCount,
        truncated: input.truncated,
        timestamp,
        relativeTime: options.formatRelativeTime?.(timestamp) ?? null,
      };
    }
    
    /**
     * Interleave operator messages into a provider event timeline.
     *
     * Ordering rules, in priority order:
     *  1. Pending messages always render last. They have not reached the provider,
     *     so placing them mid-stream would imply the agent had already seen them —
     *     the single case where a wrong position would be actively misleading.
     *  2. Delivered messages are inserted before the first provider event whose
     *     timestamp is not earlier than the delivery time.
     *  3. Events with an unparsable timestamp never trigger a flush, so a malformed
     *     stamp can only delay a user message, never reorder the provider stream.
     *
     * Note on precision: several providers emit no per-envelope timestamps, so
     * parseAgentStreamOutput synthesizes monotonic ones from the execution start.
     * Those can drift from wall clock over a long goal, which may shift a delivered
     * message by a few positions. That is accepted as cosmetic; rule 1 protects the
     * only case where placement carries real meaning.
     */
    export function mergeGoalTimeline<T extends TimelineEvent>(
      events: readonly T[],
      inputs: readonly GoalInput[] = [],
      options: MergeOptions = {},
    ): TimelineEvent[] {
      if (inputs.length === 0) return [...events];
    
      const delivered = inputs
        .filter(input => input.state !== 'pending')
        .map(input => ({ input, at: Date.parse(anchorTimestamp(input)) }))
        .filter(entry => Number.isFinite(entry.at))
        .sort((left, right) => left.at - right.at);
      // Anything we could not place chronologically (pending, or an unparsable
      // timestamp) is appended rather than dropped — losing a user's own message is
      // strictly worse than showing it slightly out of order.
      const trailing = inputs.filter(
        input => input.state === 'pending' || !Number.isFinite(Date.parse(anchorTimestamp(input))),
      );
    
      const merged: TimelineEvent[] = [];
      let cursor = 0;
      for (const event of events) {
        const eventAt = Date.parse(event.timestamp ?? '');
        if (Number.isFinite(eventAt)) {
          while (cursor < delivered.length && delivered[cursor].at <= eventAt) {
            merged.push(toTimelineEvent(delivered[cursor++].input, options));
          }
        }
        merged.push(event);
      }
      while (cursor < delivered.length) merged.push(toTimelineEvent(delivered[cursor++].input, options));
      for (const input of trailing) merged.push(toTimelineEvent(input, options));
      return merged;
    }

    File: propr-ui/src/components/TaskDetails/ExecutionEventUtils.ts

    Why this file: it centralizes the gutter label, colour and one-line summary for every event category. Adding the branches here means the terminal view gets correct labelling without touching its render tree.

    Add a user_input branch to getCategoryDisplay (before its existing thought handling) and to extractEventSummary:

    --- a/propr-ui/src/components/TaskDetails/ExecutionEventUtils.ts
    +++ b/propr-ui/src/components/TaskDetails/ExecutionEventUtils.ts
    @@
     export const getCategoryDisplay = (event: LiveEvent): { label: string; color: string } => {
    +  // Sky is reserved for the operator's own voice so a scanning eye can separate
    +  // "what I told it" from agent thought (blue), action (emerald) and search (purple).
    +  if (event.type === 'user_input') return { label: 'YOU', color: 'text-sky-400' };
    @@
     export const extractEventSummary = (event: LiveEvent): string => {
    +  if (event.type === 'user_input') {
    +    // Show only the first line: a correction can be thousands of characters and
    +    // the collapsed row must stay one line tall.
    +    const firstLine = (event.content || '').split('\n')[0].trim();
    +    return firstLine.length > 150 ? `${firstLine.slice(0, 150)}...` : firstLine || 'Message sent';
    +  }

    File: propr-ui/src/components/TaskDetails/ExecutionEventHelpers.tsx

    Why this file: it owns EventIcon, the left-gutter glyph. Without a branch here a user message would silently reuse the agent-thought icon and become visually indistinguishable — defeating the purpose of the feature.

    --- a/propr-ui/src/components/TaskDetails/ExecutionEventHelpers.tsx
    +++ b/propr-ui/src/components/TaskDetails/ExecutionEventHelpers.tsx
    @@
    -import { ... } from 'lucide-react';
    +import { UserRound, ... } from 'lucide-react';
    @@
     export const EventIcon: React.FC<{ event: LiveEvent }> = ({ event }) => {
    +  // Matches the sky accent used by getCategoryDisplay, so icon and label read as
    +  // one unit rather than two independent signals.
    +  if (event.type === 'user_input') return <UserRound className="h-3 w-3 text-sky-400" />;

    File: propr-ui/src/components/TaskDetails/ExecutionEventLog.tsx

    Why this file: the raw terminal view must be able to expand a long correction. Rendering the body as pre-formatted text (not Markdown) is deliberate — this is the operator's literal input and the terminal view's contract is verbatim output.

    --- a/propr-ui/src/components/TaskDetails/ExecutionEventLog.tsx
    +++ b/propr-ui/src/components/TaskDetails/ExecutionEventLog.tsx
    @@
    +// Separate component for an operator steering message
    +const UserInputContent: React.FC<{ event: LiveEvent }> = ({ event }) => (
    +  <div className="text-xs font-mono text-sky-100 pl-2">
    +    {/* Rendered verbatim, not through MarkdownRenderer: the raw terminal view's
    +        contract is "exactly what was sent", and Markdown would silently rewrite
    +        backticks, lists and underscores that the user typed intentionally. */}
    +    <pre className="whitespace-pre-wrap break-words">{event.content}</pre>
    +    {event.truncated && (
    +      <span className="mt-1 block text-[10px] uppercase tracking-widest text-zinc-500">
    +        Message truncated for display
    +      </span>
    +    )}
    +  </div>
    +);
    +
     // Expanded content component to reduce complexity
     const ExpandedContent: React.FC<{
       event: LiveEvent;
       taskInfo: TaskInfo | null;
       resultText: string;
       language: string;
     }> = ({ event, taskInfo, resultText, language }) => {
    +  if (event.type === 'user_input') {
    +    return <UserInputContent event={event} />;
    +  }
    +
       if (event.type === 'thought' && event.content) {
         return <ThoughtContent content={event.content} />;
       }
    @@
     const hasExpandableContent = (event: LiveEvent, resultText: string): boolean => {
       return (
    +    // Same 60-character threshold as thoughts: anything shorter already fits in
    +    // the collapsed summary row, so a chevron would expand to identical text.
    +    (event.type === 'user_input' && !!event.content && event.content.length > 60) ||
         (event.type === 'thought' && !!event.content && event.content.length > 60) ||

    Also extend computeSummaryMessage so the collapsed footer can describe a trailing user message:

    @@
       if (event.type === 'thought' && event.content) {
         const truncated = event.content.slice(0, 150).replace(/\n/g, ' ');
         return `Thinking: ${truncated}${event.content.length > 150 ? '...' : ''}`;
       }
     
    +  if (event.type === 'user_input' && event.content) {
    +    // The collapsed bar is the only visible row when the log is closed; showing
    +    // the operator's last message there confirms the send without expanding.
    +    const truncated = event.content.slice(0, 150).replace(/\n/g, ' ');
    +    return `You: ${truncated}${event.content.length > 150 ? '...' : ''}`;
    +  }
    +
       return '';

    File: propr-ui/src/components/TaskDetails/ThinkingLog.tsx

    Why this file: this is the default (Human readable) view, so it is where most operators will look for confirmation that their correction landed. detectThoughtType must be bypassed for user messages — running keyword heuristics over operator text would mislabel a correction containing the word "search" as agent search activity.

    --- a/propr-ui/src/components/TaskDetails/ThinkingLog.tsx
    +++ b/propr-ui/src/components/TaskDetails/ThinkingLog.tsx
    @@
    -import { Lightbulb, Wrench, Search, CheckCircle2 } from 'lucide-react';
    +import { Lightbulb, Wrench, Search, CheckCircle2, UserRound } from 'lucide-react';
    @@
    +const UserInputEntry: React.FC<{ event: ThinkingLogEvent }> = ({ event }) => (
    +  // A left accent bar plus an inset background makes an operator message read as
    +  // a distinct speech turn rather than another line of agent narration.
    +  <div className="py-3 border-b border-slate-50 last:border-b-0">
    +    <div className="flex items-start gap-3">
    +      <div className="flex-shrink-0 w-[100px] flex flex-col items-start">
    +        <div className="flex items-center gap-1.5">
    +          <UserRound className="h-3 w-3 text-sky-500/70" />
    +          <span className="text-[11px] font-mono font-bold uppercase tracking-tighter text-sky-600">
    +            YOU
    +          </span>
    +        </div>
    +        {event.relativeTime && (
    +          <span className="font-mono text-[10px] text-slate-500 mt-0.5 ml-[18px]">
    +            {event.relativeTime}
    +          </span>
    +        )}
    +      </div>
    +      <div className="flex-1 min-w-0 overflow-hidden">
    +        <div className="border-l-2 border-sky-300 bg-sky-50/60 px-3 py-2">
    +          {/* Verbatim, not Markdown: this is exactly what the operator typed. */}
    +          <p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-slate-800">
    +            {event.content}
    +          </p>
    +          <div className="mt-1.5 flex flex-wrap items-center gap-2 text-[10px] text-slate-500">
    +            {event.inputState === 'pending' && (
    +              // The one status that changes what the operator should expect next:
    +              // the agent has not seen this yet.
    +              <span className="rounded-full bg-amber-100 px-2 py-0.5 font-semibold text-amber-800">
    +                Queued for the next provider boundary
    +              </span>
    +            )}
    +            {event.inputState === 'undeliverable' && (
    +              <span className="rounded-full bg-red-100 px-2 py-0.5 font-semibold text-red-800">
    +                Not delivered
    +              </span>
    +            )}
    +            {(event.attachmentCount ?? 0) > 0 && (
    +              <span>
    +                {event.attachmentCount} file{event.attachmentCount === 1 ? '' : 's'} attached
    +              </span>
    +            )}
    +            {event.truncated && <span>Message truncated for display</span>}
    +          </div>
    +        </div>
    +      </div>
    +    </div>
    +  </div>
    +);
    +
     const TerminalLogEntry: React.FC<TerminalLogEntryProps> = ({ event, todoContext, isHighlighted }) => {
    +  // Branch before detectThoughtType: its keyword heuristics are tuned for agent
    +  // narration and would mislabel operator text ("search the API" -> SEARCH).
    +  if (event.type === 'user_input') {
    +    return <UserInputEntry event={event} />;
    +  }
    +
       const displayContent = formatReviewPromptOverview(event.content) ?? event.content;

    Also relax the interface so merged entries type-check:

    @@
     interface ThinkingLogEvent extends LiveEvent {
       relativeTime?: string | null;
     }

    (no change needed if LiveEvent was widened as specified above — verify it compiles).


    File: propr-ui/src/pages/GoalsPage.tsx

    Why this file: this is the only place that knows both halves — goal.inputs from the API and live.events from the socket/poll projection. Wiring the merge here (rather than inside useTaskLiveData) keeps the task detail page untouched.

    --- a/propr-ui/src/pages/GoalsPage.tsx
    +++ b/propr-ui/src/pages/GoalsPage.tsx
    @@
     import { GoalAttachmentInput } from '../components/Goals/GoalAttachmentInput';
     import { clipboardImageFiles } from '../components/Goals/goalAttachmentUtils';
    +import { mergeGoalTimeline } from '../components/Goals/goalTimeline';
    +import { formatRelativeTime } from '../components/TaskDetails/utils';
    @@
       const goalHistory = useMemo(() => goal?.startedAt
         ? [{ state: 'CLAUDE_EXECUTION', timestamp: goal.startedAt }]
         : [], [goal?.startedAt]);
       const thinkingLog = useThinkingLog(live, goalHistory);
    +
    +  // Merge once per view. The readable view consumes the thought-filtered list,
    +  // the terminal view consumes the full provider stream, but both must show the
    +  // operator's messages in the same positions, so they share one merge rule.
    +  const timelineBase = goal?.startedAt ?? goal?.createdAt;
    +  const mergeOptions = useMemo(() => ({
    +    formatRelativeTime: (timestamp: string) => formatRelativeTime(timestamp, timelineBase),
    +  }), [timelineBase]);
    +  const readableTimeline = useMemo(
    +    () => mergeGoalTimeline(thinkingLog.thinkingLogWithTimestamps, goal?.inputs ?? [], mergeOptions),
    +    [thinkingLog.thinkingLogWithTimestamps, goal?.inputs, mergeOptions],
    +  );
    +  const terminalTimeline = useMemo(
    +    () => mergeGoalTimeline(live.events, goal?.inputs ?? [], mergeOptions),
    +    [live.events, goal?.inputs, mergeOptions],
    +  );

    Then swap the two render sites to use the merged lists:

    @@
               {outputMode === 'readable'
    -            ? <div className="min-h-32 py-4">{thinkingLog.thinkingLogWithTimestamps.length > 0
    -              ? <ThinkingLog events={thinkingLog.thinkingLogWithTimestamps} todos={live.todos} />
    +            ? <div className="min-h-32 py-4">{readableTimeline.length > 0
    +              ? <ThinkingLog events={readableTimeline} todos={live.todos} />
                   : <p className="text-sm text-slate-500">No human-readable output yet.</p>}</div>
    -            : <div className="mt-4 min-h-32 bg-slate-950 p-4 text-slate-100">{live.events.length > 0
    -              ? <ExecutionEventLog events={live.events} collapsed={false} onToggleCollapse={() => undefined} lastThought={thinkingLog.lastThought} isTaskActive={mutable && goal.desiredState === 'running'} taskInfo={null} />
    +            : <div className="mt-4 min-h-32 bg-slate-950 p-4 text-slate-100">{terminalTimeline.length > 0
    +              ? <ExecutionEventLog events={terminalTimeline} collapsed={false} onToggleCollapse={() => undefined} lastThought={thinkingLog.lastThought} isTaskActive={mutable && goal.desiredState === 'running'} taskInfo={null} />
                   : <p className="text-sm text-slate-400">No terminal output yet.</p>}</div>}

    Note on formatRelativeTime: verify the exported signature in propr-ui/src/components/TaskDetails/utils.ts. If it does not accept a base timestamp as its second argument, adapt the single mergeOptions callback above rather than changing the merge helper — the helper deliberately takes a formatter callback so this stays a one-line adaptation.


    File: propr-ui/src/components/Goals/goalTimeline.test.ts (new file)

    Why this file: the ordering rule is the only non-obvious logic in this change. Testing it as a pure function keeps the guarantee ("pending always last") locked in without rendering a page or mocking sockets.

    import { describe, expect, it } from 'vitest';
    import { mergeGoalTimeline } from './goalTimeline';
    import type { GoalInput } from '../../api/goals';
    
    const input = (overrides: Partial<GoalInput>): GoalInput => ({
      id: 'input-1',
      message: 'Use the existing API shape.',
      state: 'delivered',
      createdAt: '2026-09-22T10:00:00.000Z',
      deliveredAt: '2026-09-22T10:00:05.000Z',
      attachmentCount: 0,
      truncated: false,
      ...overrides,
    });
    
    const event = (id: string, timestamp: string) => ({
      id, type: 'thought' as const, content: id, timestamp,
    });
    
    describe('mergeGoalTimeline', () => {
      it('places a delivered message at its delivery position', () => {
        const merged = mergeGoalTimeline(
          [event('a', '2026-09-22T10:00:00.000Z'), event('b', '2026-09-22T10:00:10.000Z')],
          [input({})],
        );
        expect(merged.map(entry => entry.id)).toEqual(['a', 'goal-input-input-1', 'b']);
        expect(merged[1].type).toBe('user_input');
      });
    
      it('pins pending messages to the end so they never imply prior delivery', () => {
        const merged = mergeGoalTimeline(
          [event('a', '2026-09-22T10:00:30.000Z')],
          [input({ id: 'p', state: 'pending', deliveredAt: null, createdAt: '2026-09-22T10:00:01.000Z' })],
        );
        expect(merged.map(entry => entry.id)).toEqual(['a', 'goal-input-p']);
        expect(merged[1].inputState).toBe('pending');
      });
    
      it('appends rather than drops a message whose timestamp cannot be parsed', () => {
        const merged = mergeGoalTimeline(
          [event('a', '2026-09-22T10:00:00.000Z')],
          [input({ id: 'bad', deliveredAt: 'not-a-date', createdAt: 'not-a-date' })],
        );
        expect(merged.map(entry => entry.id)).toEqual(['a', 'goal-input-bad']);
      });
    
      it('returns the provider stream untouched when there are no inputs', () => {
        const events = [event('a', '2026-09-22T10:00:00.000Z')];
        expect(mergeGoalTimeline(events, [])).toEqual(events);
      });
    });

    File: packages/api/test/goalProjection.test.ts

    Why this file: it already owns the projection's redaction contract. Extending it here keeps "what the goal endpoint is allowed to return" in one place, including the new path-leak guarantee.

    Add a case that seeds goal_inputs with one of each kind and asserts the filtering, stripping and bounding:

    it('projects only operator messages and never their stored attachment paths', async () => {
      await database('goal_inputs').insert([
        {
          input_id: 'ctx-1', goal_id: 'goal-1', owner_id: 'owner-1', idempotency_key: 'k1',
          operation: 'goal.context', payload_hash: 'h1', kind: 'context',
          message: 'ProPR delivery policy', state: 'delivered', created_at: '2026-09-22T10:00:00.000Z',
        },
        {
          input_id: 'inp-1', goal_id: 'goal-1', owner_id: 'owner-1', idempotency_key: 'k2',
          operation: 'goal.input', payload_hash: 'h2', kind: 'input',
          message: 'Use the existing API shape.\n\nAttached files:\nreference.png (/tmp/git-processor/goal-attachments/goal-1/attachment-1.webp)',
          state: 'delivered', created_at: '2026-09-22T10:01:00.000Z', delivered_at: '2026-09-22T10:01:02.000Z',
        },
      ]);
    
      const projection = await serializeGoal(database, redis, row);
    
      // The ProPR-authored context message is control plane, not user speech.
      expect(projection.inputs.map(entry => entry.id)).toEqual(['inp-1']);
      expect(projection.inputs[0].message).toBe('Use the existing API shape.');
      expect(projection.inputs[0].attachmentCount).toBe(1);
      // The hard guarantee: no internal runtime path escapes to the browser.
      expect(JSON.stringify(projection.inputs)).not.toContain('/tmp/git-processor');
    });
    
    it('omits inputs when the list endpoint opts out', async () => {
      const projection = await serializeGoal(database, redis, row, { includeInputs: false });
      expect(projection.inputs).toEqual([]);
    });

    File: propr-ui/src/pages/GoalsPage.test.tsx

    Why this file: it is the end-to-end guard for the goal detail view. Asserting here proves the whole chain — API type, merge helper, ThinkingLog branch — actually renders, not just that each part compiles.

    Add inputs to the existing goal fixture and a new case:

    it('shows operator corrections in the goal output timeline', async () => {
      vi.mocked(goalsApi.getGoal).mockResolvedValue({
        goal: {
          ...goal,
          inputs: [
            {
              id: 'input-1', message: 'Use the existing API shape.', state: 'delivered',
              createdAt: '2026-09-22T10:00:00.000Z', deliveredAt: '2026-09-22T10:00:02.000Z',
              attachmentCount: 0, truncated: false,
            },
            {
              id: 'input-2', message: 'Also update the changelog.', state: 'pending',
              createdAt: '2026-09-22T10:05:00.000Z', deliveredAt: null,
              attachmentCount: 1, truncated: false,
            },
          ],
        },
      });
      vi.mocked(getTaskLiveDetails).mockResolvedValue({
        events: [{ id: 'thought-1', type: 'thought', content: 'Implementing the API.', timestamp: '2026-09-22T10:00:10.000Z' }],
        todos: [], currentTask: 'Implement API', tokenUsage: null,
      });
    
      render(<MemoryRouter initialEntries={['/goals/goal-1']}><Routes><Route path="/goals/:goalId" element={<GoalsPage />} /></Routes></MemoryRouter>);
    
      // The delivered correction is part of the default readable timeline.
      expect(await screen.findByText('Use the existing API shape.')).toBeInTheDocument();
      expect(screen.getAllByText('YOU').length).toBeGreaterThan(0);
      // A pending correction must be explicitly marked so the operator knows the
      // agent has not acted on it yet.
      expect(screen.getByText(/Queued for the next provider boundary/)).toBeInTheDocument();
      expect(screen.getByText('1 file attached')).toBeInTheDocument();
    
      // The same message survives the view toggle.
      fireEvent.click(screen.getByRole('button', { name: 'Raw terminal' }));
      expect(screen.getAllByText(/Use the existing API shape\./).length).toBeGreaterThan(0);
    });
  2. propr-dev commented on Sep 23, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5
    • Branch: 2467/claude-opus-5-show-user-corrective-mess-20260923-0819-buv
    • Base Branch: main
    • Worktree: issue-2467-20260923-0819-claude-opus-5-buv

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions