Skip to content

feat(conversations): Derive one Conversation status - #2951

Merged
BYK merged 45 commits into
mainfrom
feat/conversation-status-7a
Nov 19, 2026
Merged

BYK merged 45 commits into
mainfrom
feat/conversation-status-7a

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

PR 7a of #2792 / part of #2888.

One place derives the status of a Conversation's own work: conversationStatusSql in src/chat/conversations/sql/status.ts. Each Conversation is needs_input, working or done. Pinned and archived stay flags, not statuses.

Precedence

needs_input > working > done. The first one that applies wins.

  • needs_input: the work waits on a person. Each wait names who it waits on:
    • an open action Review item that the Conversation added waits on its assignees, or on Everyone. This applies while a Turn runs too;
    • a sign-in wait (an authorization_requested Event that is the newest Turn or authorization Event and is less than 24 hours old) waits on that person;
    • the work waits on its starter: the latest Turn failed, the latest Brief outcome is partial or blocked, or the starter has not read the latest answer. These starter rules apply only when no Turn is queued or running.
  • working: a Turn is queued or running (execution pending, running or paused, plus the legacy awaiting_resume).
  • done: anything else. This covers a done Brief, a read answer, a stop, an abandoned or idle Conversation, and a parent that waits for its children.

The starter is the User of the root's actor: the person whose message started the root, or the creator of an Automation run. A Task reports to its parent, so only a root, an Automation run or a Thread waits on its starter. A failed Task reads done, and a stop ends every starter wait.

An answer is the latest assistant Message when the latest Brief is answered or does not cover it. A done Brief that covers it needs no read. The starter has read it when any of these is true:

  • a root delivered it to its Slack Location;
  • the starter wrote a later Message;
  • the starter's dashboard read position reaches it.

The Bugbot finding ("Live turns hide behind needs_input") is fixed in conversationWaitsOnStarterSql: an unread answer, a partial/blocked Brief or an old failed Turn no longer reads needs_input while the next Turn runs. An open action item still does, because a person must act on it while the Turn runs.

Readers

Readers no longer derive status. The detail, feed, Threads, agent tree, locations, people (list and Turn counts), MCP searchConversations and getConversation, aggregate counts and feed version tokens all select the SQL value. Review item writes touch the detail version of the Conversation that added the item, so polls see needs_input change. Auto-archive keeps its own check.

Live Turns: turnActive

needs_input can now hide a running Turn, so status no longer tells the dashboard whether to poll. The summary and detail get a required turnActive: boolean: a Turn is queued or running. It comes from the execution status, through the same list of execution statuses as conversationIsActiveSql. No existing field fit: Turn lifecycle events miss a queued Turn, feed rows have no events, and a Turn parked on sign-in has an open turn_started.

The dashboard reads it through one helper, conversationTurnIsActive (src/client/conversations/turnActivity.ts). These use it: detail polling (conversationDetailIsLive), the thinking indicator (conversationIsResponding), the live page state in both layouts (Stop, composer, history), live cost and runtime, the menu, Quick question, the pending transcript label, the In flight group, and every running spinner that takes the place of a row's age (feed cards, Inbox rows, the sidebar, Thread rows, the In flight nav). The feed version token already treats a row as running by its execution status, so these match it. Status icons and pills still show status.

MCP returns turnActive on searchConversations and getConversation. getConversation and the MCP docs say to poll until turnActive is false and hasMore is not set, so a follow loop does not stop while a Turn runs behind needs_input.

The iOS app reads needs_input, working and done, and polls and shows work on turnActive. The "Turn failed" / "Stopped" transcript row is gone, because the public API no longer tells the two apart. The Swift changes are not compiled here: this sandbox has no Swift toolchain.

needs_input with a running Turn: polls, shows thinking needs_input, no Turn: no polling, no thinking
running idle

Other dashboard changes: VisualStatus and the visualStatusFor* and isIdleConversation helpers are gone. The API status is the only input for status display. needs_input shows as amber "Needs input" text, and done shows nothing. The per-viewer "waiting on you" override for children is gone. It read root ids only, so no child ever matched it.

A failed Turn needs input (dark) Light
failed failed light
Mobile (dark) Mobile (light)
failed mobile failed mobile light
A nested Thread with an open action item (dark) Light
thread thread light

(Mock dashboard data.)

Migration

0130_review_item_status_index adds only the open action Review item partial index, which the needs_input check reads. It uses CREATE INDEX CONCURRENTLY. No column is added. The failed-Turn check reads the existing junior_conversation_events_type_idx.

Notes for review

  • The sign-in wait ends on the app clock, which also dates the request, not on the database's now(). So the Conversation record columns are built for each query.
  • Status reads Turn events, so a Conversation whose last Turn failed before this release also reads needs_input until its next Turn.
  • needs_input keys on the adding Conversation (added_by_conversation_id).
  • The latest answer is picked by seq. That read uses junior_conversation_events_message_role_idx and a top-N sort, not the type index. EXPLAIN ANALYZE with seeded rows: 0.056 ms for a typical Conversation, 2.3 ms for one with 10,000 assistant Messages.
  • The child-agents API (/agents) keeps the agent invocation status. Only the Conversation status changed.

Follow-ups

via @dcramer, @BYK.

--

View Session [Sentry]

Derive the status of a Conversation's own work in one SQL expression,
conversationStatusSql: active > stopped > failed > needs_input > idle.
The API, MCP, searchAgents, counts, feed tokens, auto-archive, and the
dashboard read it. completed is no longer a Conversation status.

A failed Turn is a durable input: the event append writes failed_turn_id.
An open action Review item that a Conversation added, assigned to a User
or Everyone, makes it needs_input, and Review item writes touch its
detail version.

Part of #2888 (PR 7a of #2792).
@vercel

vercel Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 19, 2026 11:02am UTC

Request Review

@dcramer
dcramer marked this pull request as ready for review November 9, 2026 00:43
@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 9, 2026
@blacksmith-sh

This comment has been minimized.

Mocks now send idle or needs_input instead of completed. Thread status
tests read the API status rather than a mocked waiting list that only
holds root ids in production.

Co-Authored-By: David Cramer <[email protected]>
…tus-7a

Co-Authored-By: David Cramer <[email protected]>

# Conflicts:
#	packages/junior/migrations/meta/0088_snapshot.json
#	packages/junior/migrations/meta/_journal.json
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

141 screenshot changes — 141 changed · 0 added · 0 removed

Review screenshots in Frameshift

Automation Overview Run Details · Desktop
Automation Overview Run Details · Desktop
Changed
Automation Run Details · Desktop
Automation Run Details · Desktop
Changed
Automation Skill Editor · Desktop
Automation Skill Editor · Desktop
Changed
Automations Runs Filters · Desktop
Automations Runs Filters · Desktop
Changed
Code · Desktop
Code · Desktop
Changed
Composer Skill Card · Desktop
Composer Skill Card · Desktop
Changed
Show 12 more changed screenshots
Composer Skill Card · Mobile
Composer Skill Card · Mobile
Changed
Composer Skill Details · Desktop
Composer Skill Details · Desktop
Changed
Composer Skill Menu · Mobile
Composer Skill Menu · Mobile
Changed
Composer Skill Menu Expanded · Mobile
Composer Skill Menu Expanded · Mobile
Changed
Conversation Attached Linked Work · Desktop
Conversation Attached Linked Work · Desktop
Changed
Conversation Attached Linked Work Denied · Desktop
Conversation Attached Linked Work Denied · Desktop
Changed
Conversation Attached Linked Work Denied Light · Desktop
Conversation Attached Linked Work Denied Light · Desktop
Changed
Conversation Attached Linked Work Light · Desktop
Conversation Attached Linked Work Light · Desktop
Changed
Conversation Attachment · Desktop
Conversation Attachment · Desktop
Changed
Conversation Attachment Zoom · Desktop
Conversation Attachment Zoom · Desktop
Changed
Conversation Attachment Zoom · Mobile
Conversation Attachment Zoom · Mobile
Changed
Conversation Child Agent Drawer · Desktop
Conversation Child Agent Drawer · Desktop
Changed

123 more changed screenshots in Frameshift.

dcramer added a commit that referenced this pull request Nov 9, 2026
…pair (#2959)

Refs #2890. First slice for the Conversation execution status and its
SQL copy.

- **SQL stores `paused`, not `awaiting_resume`.** Migration 0089 renames
old rows. Readers accept both names during rollout. #2951's status SQL
matches only `paused`.
- **One runnable check.** The duplicates in `store.ts` and `worker.ts`
are gone. The `store.ts` copy counted `failed` as runnable, so the
heartbeat sent wakes that did nothing.
- **No status repair.** The decoder and `writeConversation` no longer
turn `idle` into `running` or `pending`. `writeConversation` now rejects
a lease on any status but `running`/`paused`, and `idle` with pending
messages. No writer makes these states, and the old repair is older than
the 7-day Redis TTL.
- **Heartbeat prunes the active index under the mutation lock.** Before,
it could remove the entry of work that an append had just made runnable.

Compatibility: Redis v2 records decode unchanged. The migration changes
data only. #2951 also adds `0089`, so the second PR to merge renumbers.

Left for later: a tagged `Execution` union with one transition owner
(`paused` means three things today). Turn writes stop setting SQL
`execution_status`/`run_id` (needs #2951's `failed_turn_id`). Write the
SQL copy from the record that was just saved. Stop mirroring
`last_*_at`. Compute retry exhaustion in one place. Drop the
`awaiting_resume` reader.

<!-- junior-request-attribution:start -->
via @dcramer.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A50366cb02bdecc4b07c6dbb79288f5c0 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A50366cb02bdecc4b07c6dbb79288f5c0)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A50366cb02bdecc4b07c6dbb79288f5c0/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>
dcramer added a commit that referenced this pull request Nov 9, 2026
#2960)

Refs #2890 (Conversation stop item, first slice).

## Bug

A person stops a Slack thread while a request waits for sign-in. With
the native stop button, a dashboard Stop, or an ACP cancel, the request
keeps waiting, and a later sign-in resumes it and answers. Only the
`stop` keyword worked: on sign-in, `wasPendingAuthStopped` scanned the
thread for a skipped Message whose `skippedReason` starts with
`thread_opt_out:`. That made stop a third copy of the state, read from
Message text.

## Change

- `stopConversation` ends the stopped Conversation's own sign-in wait
with `cancelSignInWait`, as the tree stop already did for child agents.
It finds a web Turn from its auth-paused Turn record and a Slack request
from the thread's pending sign-in. Then it runs the existing
`cancelSignInPausedTurn`. That function claims the Turn
(`onlyIfAuthPaused`), so a worker that already resumed it keeps its end.
- `finishStoppedTree` uses the same function, so a child Thread with a
Slack sign-in wait also ends.
- Deleted `wasPendingAuthStopped`. The Turn record is now `abandoned`,
and the resume's `beforeStart` rejects it. The terminal state blocks the
late write.
- Deleted `stopConversationTurn` (only caller: `stopConversation`). Its
auth-paused branch asked for work only to stop it again, and the stop
wake could reach queued input first.
- MCP callback (`handlers/mcp-oauth-callback.ts`): only a newer attempt
expires a link. A sign-in that completes after its request stopped saves
the credential, does not resume the request, and shows "connected … ask
again when you need it".

UX: every stop surface acts the same. A sign-in after a stop still
connects the account for later requests. Before, the link said "will
continue the paused request". DX/AX: no stop state comes from Message
text.

## Compatibility

No storage, schema, HTTP, or plugin API change. A web Turn that waits
for sign-in now returns `no_work` from a dashboard or MCP stop instead
of `requested`. No worker runs that Turn, so `no_work` is accurate. A
keyword stop sent before the deploy, with a sign-in after it, now
resumes the request. This window is short.

## Tests

`tests/integration/slack/mcp-authorization.test.ts` uses the real Slack
ingress, queue, worker, and MCP OAuth callback. A request waits for
sign-in. The person stops it with the keyword, the native button, or
`stopConversation`, then approves the link. No answer is posted, and a
later request answers with the saved credential and no new link. Before
this change, the button and dashboard cases failed. The
`wasPendingAuthStopped` unit tests are deleted. `thread-input.test.ts`
fails with "Conversation parent changed" now and then, and it does the
same on `main` with a reused local DB.

## Left for #2890

- **Wall-clock scope:** the stop compares `stopped_at` with
`createdAtMs`, `receivedAtMs`, and the invocation `createdAtMs`. The
known gap in `session-stop.ts` is input sent before the stop but
received after it: it runs, and the Conversation stays stopped. The fix
is an ordered cutoff (`stopped{at, cutoffSeq}`). Inbound messages have
no seq yet. This needs the mailbox owner and overlaps #2951's planned
7b.
- **One transition owner** (`setConversationStop`) over
`markConversationsStopped` and `resumeStoppedConversationTree`. Best
done after 7b, which sends every stop through the tree stop.
- `isChildAgentSessionStopped` (child status, `sm-child-agents`).
Dashboard status is in #2951.
- The Redis stop key is a one-shot request to abort a run, not a copy of
the stopped state. No change.

<!-- junior-request-attribution:start -->
via @dcramer.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A1cee139607e8c64034e4556a08b57282 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A1cee139607e8c64034e4556a08b57282)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A1cee139607e8c64034e4556a08b57282/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>
@dcramer

dcramer commented Nov 9, 2026

Copy link
Copy Markdown
Member

i think we're ok using a derived status, but we should make sure that its got a clean interface/abstraction for it so we're not recomputing it in 12 different ways in 12 different locations

sentry-junior Bot and others added 3 commits November 9, 2026 23:48
Drop failed_turn_id. conversationStatusSql compares the newest turn_failed
seq with the newest turn_started and turn_completed seqs. Each max reads
the end of junior_conversation_events_type_idx. The migration keeps only
the open action Review item index.

Co-Authored-By: David Cramer <[email protected]>
Main now stores paused, not awaiting_resume, so the stub child that stays
paused reads as active.

Co-Authored-By: David Cramer <[email protected]>
@sentry-junior

sentry-junior Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Agreed. conversationStatusSql in src/chat/conversations/sql/status.ts is the only code that derives a Conversation status. Every reader selects it:

  • the detail record (api/conversations/record.ts), which the detail, the feed rows, and MCP getConversation/searchConversations read
  • the feed version token, for roots and their Threads (api/conversations/list.ts)
  • aggregate counts (api/conversations/aggregate.ts), used by stats and locations
  • auto-archive's quiet check (api/conversations/auto-archive.ts)
  • the locations list (api/locations/query.ts)
  • the people list and the people Turn counts (api/people/shared.ts)
  • the Board's working check (api/board/read.ts)
  • child agents and a child's parent (chat/agent-invocations/list.ts), which searchAgents reads
  • top-level agent search (chat/agent-invocations/search-top-level.ts)

The merge with main brought in two new readers that compared execution_status themselves: the Board and the people Turn counts. Both now select the status too.

This push also drops failed_turn_id. "The latest Turn failed" now comes from Turn lifecycle events: the newest turn_failed seq is greater than the newest turn_started and turn_completed seqs. Each of those reads the end of junior_conversation_events_type_idx. So no status input is stored outside the rows it comes from.

… as needs_input

An item with no assignees still waits for whoever can answer it. Assignee
writes no longer touch the detail, since the status no longer reads them.

Co-Authored-By: David Cramer <[email protected]>
BYK added a commit that referenced this pull request Nov 10, 2026
…out of auto-archive (#3063)

A web conversation asked for a Linear connection and parked its Turn.
Auto-archive archived it before the person connected (requested
2026-11-09 18:35 UTC, connected 2026-11-10 10:01 UTC). The feed did not
put it in Needs attention either.

A Turn that parks for authorization ends its run, so execution goes back
to `idle` and the tree is quiet. The wait exists only in the Redis Turn
record and the web connect prompt. Auto-archive and the feed do not read
either one. #2951 also counts a sign-in wait as `idle`.

The wait is now read from the durable `authorization_requested` event
(`src/chat/conversations/sql/authorization-wait.ts`). A conversation
waits when its newest request:

- has no later `authorization_completed`, `turn_started`,
`turn_completed`, or `turn_failed`. A stop or new input ends the parked
Turn with `turn_completed`.
- is less than 24 hours old. After that the MCP auth session and the
connect prompt expire, so the Turn cannot resume.

The root and every child conversation count. The check is one correlated
lookup of the newest of these events, and it runs inside reads that
already happen:

- **Auto-archive**: an extra arm in `treeIsQuiet`'s tree subquery, so a
tree that waits is not quiet. This covers the scheduled sweep and the
manual archive-done run.
- **Feed**: a column of the feed row select, so rows get
`awaitingAuthorization: true` and the dashboard's `needsAttention` puts
them in Needs attention.

| Before: parked sign-in sits under August | After: in Needs attention |
| --- | --- |
|
![before](https://junior-prod.sentry.dev/public/artifacts/5d521e58-0a1d-4d72-bd51-d875faeb14bb.png)
|
![after](https://junior-prod.sentry.dev/public/artifacts/7bb183a8-4a46-450f-b747-df996f5c42fc.png)
|

(Mock dashboard data, with `awaitingAuthorization` set by hand on
"Direct Message" for the after shot. The fixture change is not
committed.)

### Remaining risk

- The flag is per conversation, not per viewer. In a shared Slack
thread, every participant sees the wait in Needs attention, not only the
person who must connect. This matches `unfinishedWork`.
- The feed version token does not move when a wait expires after 24
hours. The row leaves Needs attention on the next feed refetch.
- A conversation that waits on a sign-in and sits outside the newest 50
feed rows is not added back the way Review items are. A wait lasts at
most 24 hours from the request, which is the conversation's latest
activity, so this case is rare.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:local%3Aweb%3A6809193e8a0495106981140e -->

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A6809193e8a0495106981140e/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
…tus-7a

Co-Authored-By: BYK <[email protected]>

# Conflicts:
#	packages/junior/migrations/meta/0124_snapshot.json
#	packages/junior/migrations/meta/_journal.json

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…ards and Thread rows

A Turn can run while the Conversation needs input. Feed cards now keep
Needs input next to the spinner, and a Thread row that needs input shows
its alert icon and a running spinner.
Main added migration 0129_review_item_answered_index. Renumber this
branch's review item status index to 0130 and regenerate its snapshot.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread apps/ios/Junior/Home/HomeScreen.swift Resolved
…om the Turn

The iOS home row keeps Needs input while a Turn runs; the spinner takes
only the date's place. Mock location and people stats count a running
Turn as active and a failed latest Turn as failed, like the server.
Resolve the InboxRow import conflict, and select the derived status in
the new person card query.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b29ee6d. Configure here.

@BYK BYK left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once this stack lands I want you to launch an investigation into the efficiency of this mechanism both in terms of DB operations and speed. We can add caching like we do for cost calculations but I'd say conversation status freshness is higher stakes than some cost being off for 5 minutes.

@BYK
BYK enabled stacked auto-merge (squash) November 19, 2026 11:52
@BYK
BYK merged commit 96b8fc4 into main Nov 19, 2026
55 checks passed
@BYK
BYK deleted the feat/conversation-status-7a branch November 19, 2026 12:00
BYK added a commit that referenced this pull request Nov 19, 2026
Stacked on #2951. Its base moves to `main` once #2951
merges.

A Conversation showed only its own status, so a root whose Task was
running, or whose child asked you something, looked idle in the side
bar.

The API now derives a tree state for each feed row and the detail, for
the viewer, from the Conversation and every child Conversation. It
builds on #2951's shared status (`needs_input` > `working` > `done`):

1. `needs_you`: the tree's `needs_input` includes you. An open action
Review item in the tree that is assigned to you, to Everyone or to no
one counts, and so does a sign-in wait for you anywhere in the tree. The
Conversation's own wait on its starter (a failed Turn, a `partial` or
`blocked` Brief, an unread answer) counts only when you are the starter.
Input that waits on another person is not shown to you.
2. `working`: a Turn is queued or running anywhere in the tree.
3. `done`: anything else.

The API also sets a separate `watching` flag when a Conversation in the
tree that is not stopped has an active Watch or a pending Timer. A
pending Timer alone sets it. `watching` is not part of the shared
status, so a watching tree stays `done` for everyone else.

The response shows only the aggregated state. It shows nothing about
private child Conversations. One grouped query over the subtree reads
the tree states for a whole page, then one batched state read checks
Watches and Timers. The query count stays the same as a tree grows, and
the feed and detail routes keep their SQL budget.

The new UI shows one icon for each Conversation in In flight, the Inbox
and Conversations rows, and the Conversation header. When more than one
applies: `needs_you` > `working` > `watching` > pinned.

- A question mark when it waits on you.
- A spinner while it works.
- A quiet eye while it watches. It blinks once every 30 s, and not under
`prefers-reduced-motion`. There is no sub-agent icon art in the repo
yet, so it uses lucide `Eye`.
- The pin when nothing else applies and it is pinned. A `done` tree that
is not pinned shows nothing.

In flight also lists Conversations whose tree needs you, works or
watches, in place with Show all. The pin order does not change.

| | Dark | Light |
|---|---|---|
| Desktop |
![](https://junior-prod.sentry.dev/public/artifacts/bb74d22e-e3fe-4907-83f0-50c46e7cfc21.png)
|
![](https://junior-prod.sentry.dev/public/artifacts/cddd39d2-fb81-4f1e-a8be-535154bd15b9.png)
|
| Mobile |
![](https://junior-prod.sentry.dev/public/artifacts/0d4ea0fb-eb02-4d16-8522-c0aa4cf3e207.png)
|
![](https://junior-prod.sentry.dev/public/artifacts/5207eeee-6ecf-4200-8f5c-cfca8717f04b.png)
|
| Header |
![](https://junior-prod.sentry.dev/public/artifacts/1f440b91-f2ec-42dc-beb5-547d1e502acb.png)
|
![](https://junior-prod.sentry.dev/public/artifacts/78165339-1cc2-4282-b232-3b1a9356d253.png)
|

(Mock dashboard data.)

### Notes for review

- Per-viewer dismiss and snooze of Everyone items come later, with the
snooze table.
- A Watch that expires on its own moves no feed token, so its row shows
`watching` until the feed reads again. A Turn that makes or cancels a
Watch or Timer, a Timer that fires, and a stop anywhere in the tree all
move it.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A7664c21d021ead501bdb002f8ed78351 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A7664c21d021ead501bdb002f8ed78351)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A7664c21d021ead501bdb002f8ed78351/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK added a commit that referenced this pull request Nov 21, 2026
…zation lookups (#3965)

The no-ids part of `GET /api/versions` (feed, Inbox items, spend) got
slower in 0.311.0. Most of that time is the feed token from
`conversationFeedVersionQuery`. #3954 covers the other
part, the per-Conversation tokens.

## Cause

Feed token time on a local prod-shaped seed: 32k roots, 100 roots with
70-node trees, about 655k events, and a 50-row page.

| Feed token shape (p50) | ms |
| --- | --- |
| 0.310.0 | 22–23 |
| + derived page status and waits-on-viewer (#2951,
#3768) | 40–42 |
| + tree state (#3672, #3768) | 61–66 |
| `main` | 80–93 |

The tree state runs the authorization-wait check on every member of
every page root's tree. It also derives the status of every Thread.
Inbox items (about 1.5 ms) and spend (about 15 ms) did not change.

These per-Conversation probes cost more than they need to:

- `conversationWaitsOnStarterSql` names the same subquery several times.
It reads the latest Brief status twice, the latest reply `seq` up to
four times, and the starter user three times. Postgres runs a subquery
at each place that names it.
- The authorization wait reads each Conversation's newest wait event
with a backward scan of the events primary key. Almost no Conversation
has a recent request, so most of these reads find nothing.

## Change

- `status.ts`: the starter-wait rule reads the starter, the latest Brief
(status and `through_seq`) and the latest reply (`seq` and Slack
delivery) once, in one row: an `offset 0` subquery plus two `lateral`
joins. The guards outside it (stopped, Task, active, failed Turn) are
the same.
- `authorization-wait.ts`: the check first looks in a new partial index
for an `authorization_requested` event inside the 24h window. With none,
the rule is false, as before. The check is a scalar subquery and not
`exists`. An `exists` lets Postgres pick a hashed subplan that reads
every recent request.
- Migration `0147` adds
`junior_conversation_events_authorization_request_idx` on
`(conversation_id, created_at) WHERE type = 'authorization_requested'`,
built `CONCURRENTLY IF NOT EXISTS` like `0090`.

No status or token changes. On the seed, the feed token and the status,
waits-on-user and authorization-wait values of all ~39k Conversations
are identical to `main`. That includes live, expired, other-person and
Turn-ended requests.

## Before / after (local seed)

| Feed token | `main` | This PR |
| --- | --- | --- |
| p50, JIT off | 79.5–93.1 ms | 57.2–66.8 ms |
| Shared buffers hit | 49,397 | 35,734 |
| Estimated plan cost | 34,834 | 23,076 |
| Tree-state subplan (50 loops) | 49.9 ms | 30.4 ms |
| Authorization lookups (3,039 tree members) | 18.2 ms | 6.1 ms |

The whole no-ids statement is 73–85 ms p50 on the seed after this
change. It shrinks the 0.311.0 regression but does not remove it. The
tree state does per-member work that 0.310.0 did not: an Inbox probe, an
authorization check, and a status for each Thread. A larger gain needs a
cheaper tree-state definition. The plan cost goes down, so the statement
is not nearer to `jit_above_cost`.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A49221e97cd717f9141560b0efd29c5ae -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A49221e97cd717f9141560b0efd29c5ae)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A49221e97cd717f9141560b0efd29c5ae/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
dcramer added a commit that referenced this pull request Nov 22, 2026
…s stopped (#3962)

PR 7b of #2792 / part of #2888.

## Rule change

Automated input is held only while `stopped_at` is set. A Conversation
whose last Turn failed now runs Watch Events and other automated input
like any other Conversation, so the "Given `failed`" scenarios in #2888
now run instead of holding. Stopped stays a flag next to status. The
#2951 order `needs_input` > `working` > `done` does not change.

## One hold check

`enqueueAutomatedInput` in `conversations/session-stop.ts` is the only
place that decides a hold. Watch Events, top-level agent messages, and
child results all go through it. It checks the stop under the mailbox
lock. Held input is saved as a skipped Message and never reaches
`pending`, so it cannot race a stop.

Removed, because the hold check replaces them:
- the `admitAutomatedTurn` drop and refuse paths, and
`AgentMessagePausedError`
- the child-result bypass
- the rule that non-Watch Events after a stop still run
(`skipInputAfterConversationStop`)
- the receiver-stop drops in `routeChildInput`
- `skipUnreadResults`

## One tree stop and its resume

`stopConversationTree` is used by the person stop, `stopAgent`, and the
automated-turn limit. It writes `stopped_at` in one transaction, with
row locks taken in id order. It holds the automated input that already
waits in each mailbox, ends a Turn that waits for sign-in, and asks each
running Turn to stop. `resumeConversationTree` ends the stop in one
transaction with the same lock order. A person's input and new parent
work both resume through it.

- Every Turn that a stop ends writes one `turn_completed` with
`cancelled`. This includes the paused-turn auth-mismatch path, which
before ended a Turn with no terminal event.
- `stopAgent` keeps the child's Watches, so `cancelWatches` is gone.
- The automated-turn limit now only counts Turns. When a Turn reaches
the limit, it stops the tree and posts its existing notice. There is no
separate pause path, no notice claim, and no child-to-parent notice.

`design/child-agents.md` now states the hold rule.

## Follow-up

7c continues #2888.

<!-- junior-request-attribution:start -->
via @dcramer.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A9907647b73904de09e6bb8d25d4fc2ad -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A9907647b73904de09e6bb8d25d4fc2ad)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A9907647b73904de09e6bb8d25d4fc2ad/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>
armcknight added a commit that referenced this pull request Nov 23, 2026
The implements a real PKCE OAuth flow for the iOS app using the existing
custom schema callback. This is technically possible to be cloned by
imposter apps; the alternative is to host a `apple-app-site-association`
file on the server identifying legal clients with a regular HTTPS call
back URL, but this change does not represent a regression in security
posture. We can consider the site association file in a later PR.

# Slop

Junior now knows the iOS app's OAuth client, so sign-in no longer
depends on a hosted Client ID Metadata Document.

The app's `client_id` was a raw GitHub URL on the PR branch of #3544.
GitHub deleted that branch after the merge, so the URL returned 404, and
every sign-in to a real Junior failed with "The client ID is not a valid
client metadata document URL." A raw GitHub URL also proves nothing
about who owns the client, because anyone can host a file on that host.

The change follows how the Seer Apple apps sign in to Sentry: the server
knows the client, and the redirect uses the app's own URL scheme.

- `JUNIOR_IOS_CLIENT` in `client-metadata.ts` has the ID
`https://junior.sentry.dev/clients/ios` and the redirect
`junior-ios://oauth/callback`. `resolveMcpClient` returns it without a
fetch. The ID stays an HTTPS URL, so it passes the existing client ID
rules, and the consent page shows `junior.sentry.dev`. Nothing is served
at that URL, and the app sends this ID, so it must not change.
- Only this client may use a custom-scheme redirect, and only that exact
URI. Other CIMD clients still need `https:` or loopback `http:`, because
any app can claim a URL scheme. `redirectUriMatches` now takes the
client, so it can apply this rule.
- The app gets the redirect from `ASWebAuthenticationSession`, which
gives a scheme redirect only to the app that opened the sheet. The
`LoopbackReceiver` NWListener and `oauth-client.json` are deleted. The
mock server also accepts the new redirect.

A server that runs an older Junior rejects the new client ID. So the app
can sign in to prod only after a release with this change. Prod also
needs a release with #2951 (`turnActive`), because the app cannot read
`searchConversations` results from 0.310.0.

We could also keep a CIMD document at the new URL, so that older servers
still accept the app. We did not, because prod is the only known server
for the app.

No screenshot test applies: the sign-in screen does not change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: andrew <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — b29ee6d1 Deployed Nov 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants