Repository navigation
refactor(site/src/pages/AgentsPage): require chat IDs in chat store helpers - #29888
Merged
Merged
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
This was referenced Sep 25, 2026
Merged
Closed
Closed
Closed
…elpers The chat page only renders once the route has a chat ID, and every production caller passes a non-empty `chat.id`. Chat-scoped hooks and storage helpers still accepted `string | undefined` and re-checked it, so their `!chatID` guards were dead. Narrow `chatID`/`chatId`/`agentId`/`organizationId` to `string` in `useChatStore`, `useConversationEditingState`, `useChatToolInvalidations`, `useWorkspaceWatch`, `useGitWatcher`, `useChatDraftAttachments`, `runPromoteQueuedMessage`, and the right-panel, sidebar and draft attachment storage helpers, then delete the guards. Chat store methods that only ever receive arrays or states (`replaceMessages`, `setQueuedMessages`, `applyPromoteRefetchQueuedMessages`, `applyServerChatStatus`, `setRetryState`, `setReconnectState`) drop `undefined`/`null` from their parameters. `chatRecordUpdatedAt` becomes required so a caller cannot silently disable the status resync. Tests that passed `undefined` or `""` for values production never sends are removed or updated.
DanielleMaywood
force-pushed
the
nullability/chat-id-store
branch
from
September 29, 2026 14:28
f7814ee to
20445d9
Compare
jakehwll
approved these changes
Oct 6, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The chat page only renders once the route has a chat ID (
KeyedAgentChatPageshows the not-found view otherwise), and every production caller passeschat.idor that route param. Chat-scoped hooks and storage helpers still acceptedstring | undefinedand re-checked it, so those!chatIDguards were dead code.This narrows those parameters to
stringand deletes the guards. The same applies to chat store methods that only ever receive arrays or states (replaceMessages,setQueuedMessages,applyPromoteRefetchQueuedMessages,applyServerChatStatus,setRetryState,setReconnectState).useChatStore'schatRecordUpdatedAtbecomes required, because omitting it silently disabled the status resync.Tests that passed
undefinedor""for values production never sends are removed. TheuseChatStoretests now passchatRecordUpdatedAt.tscreported no production errors after narrowing, which confirms that no production caller passes a nullable value.aiGatewayDisabledstays optional: it defaults tofalse, and requiring it would churn 75 test call sites for no safety gain.This is the first of several AgentsPage PRs. The findings came from a TypeScript compiler API script (kept out of the repo) that builds a graph of values flowing into nullable params and props, and flags slots that never receive null or undefined from production code. This PR removes 35 of the 112 dead data slots it found.
Plan and methodology
Plan: finding misplaced nullability in
site/src/pages/AgentsPageStatus: brainstorm plus feasibility spike. No repo changes made.
Decisions
/home/coder/nullflow/). It is never committed.site/src/pages/AgentsPageonly. Slots are only reported if declared there. Callers anywhere insite/srcstill count as inflows, so a slot used from outside AgentsPage isn't narrowed by mistake.undefinedornull, the slot is dead: narrow it and update the tests.1. Problem framing
A
null | undefinedvalue goes through three roles:useQuery().data,useParams(), optional API fields (chat.last_model_config_id),Map.get,.find(),str.match()chatID: string | undefined;resolveCompactionThreshold(modelID?, thresholds?, models?: T[] | null | undefined)if (!x) return,?.,??, conditional render.rightPanelTabStorage.tsguardsif (!chatID) return []in 7 functionsA check at the origin is healthy. The smells are about carriers:
if (!chatID)repeated in many helpers).!xonnumber | undefinedorstring | undefinedalso treats0and""as absent. This is sometimes a real bug.Grep baseline (non-test, non-story files): 377 nullable-typed annotations, 911 optional
?:members, 118if (!x) return null/undefinedguards, 399??, 640?.. Grep can't tell origins from carriers. For example, mostif (!match) return undefinedhits inthinkingTitle.tsare legitimate origins. So a syntactic approach alone will mostly produce noise.2. Approaches
A. Syntactic heuristics (grep, a Biome rule, an agent that "just looks")
B. Bottom-up (start at sinks and carriers, walk toward callers)
Start from every nullable slot (param, prop, destructured prop, hook option field) and use the type checker to answer one question: "Does any call site actually pass a nullable value?"
tscconfirm.site/src).undefined). Resolved by the decision above: count only production inflows.C. Top-down (start at origins, taint forward)
List origins (query data, route params, optional API fields,
Map.get/find/match, context values) and follow each one forward to find how many hops it travels before it's narrowed, and how many guards it creates.chatonce inAgentChatPage, and pass a non-nullChatto the whole subtree").useState,useMemo, context, hook return objects, spreads ({...props}), and callbacks, and precision drops at each of these.D. Hybrid: a nullability flow graph, queried both ways (recommended)
Build one graph and run both queries on it.
useState).?.,??), and whether it's an origin.deadNullabilitymeans a slot with zero nullable inflows from production code.chainsmeans for each origin, the longest path to its first narrowing, plus the number of guards along the way.rewidenmeans a non-null argument flowing into a nullable slot, reported at the caller.3. Feasibility spike (done)
Script:
/tmp/nullspike/spike.ts(about 150 lines, TypeScript compiler API, uses the existingtypescript@6.0.2dependency). It covers call args, object-literal args, JSX attributes, and destructured props, and tracks pass-through edges between slots.site/srcin about 3.5s; about 13s total.modelOptions.tsref <- storedRef <- storedRef <- modelDisplayName.lastModelConfigID, andchatQueueReconciliation.tspromotedHeadID/queuedTail.Manually verified:
useChatStore({ chatID: string | undefined })has one production caller (AgentChatPage.tsx:371), which passesagentId, typedstring(AgentChatPage.tsx:103). The other 65 inflows are tests. This is a real finding, but it shows the tool must separate production inflows from test inflows.Known gaps in the spike:
T | undefinedwhose callers immediately use??).{...spread}props,useState, context, and generics aren't modeled.options?: {...}) are idiomatic and should be allowlisted.4. Methodology
/home/coder/nullflow/(outside the repo). It loadstypescriptfromsite/node_modulesviacreateRequire, so nothing is copied intosite/. Changes from the spike:deadmeans zero nullable production inflows. Also list the test files that pass nullable values, since those need updating.T | undefinedwhere every production caller immediately uses??,?., or a guard, or where the function never actually returns absent.falsysection:!xorx &&onnumber | undefinedorstring | undefinedslots.options?:bags, callbacks passed by reference that the tool can't follow, and slots that receive{...spread}props (report these as "unknown", never as dead).dead,chains,rewiden,falsy), each item withfile:line, inflow counts, and the upstream origin.--focus <slot>prints a Mermaid subgraph for one chain.deadbefore using it to drive fixes. Tune the exclusions as needed.deadslot:undefinedornullso they match production usage.pnpm lint:types(tsc),pnpm check(Biome), and the affected Vitest tests (pnpm test <path>), then rerun the tool. Callers that just became dead show up in the next pass.chatIDcluster (useChatStore,rightPanelTabStorage,sidebarTabStorage,draftStorage,useChatDraftAttachments,useGitWatcher,useDesktopConnection).chainsare real nullable origins carried too far. Group them by origin, rank by number of guards downstream, and decide per origin where to narrow: a loading gate, a parent component, or a converter at the API boundary. These need judgment, so I'll report each proposed narrowing point before changing it.pnpm lint:types,pnpm check,pnpm lint:oxlint,pnpm lint:compiler, and the relevant Vitest files. The final tool report (before and after counts) goes in each PR description. The tool itself isn't committed.5. Results so far
Tool:
/home/coder/nullflow/nullflow.mts, report at/home/coder/nullflow/out/report.md(about 25s per run).Fixes made after validation:
component: Foo) no longer mark props as "unknown". This had hidden 296 slots.?.,??/||, ternaries, destructuring, and dot access onRecordtypes.a && x && ...chains, and object-literal implementations of interface methods.ReactNode.ascast are flagged (e.g.useParams() as { agentId: string }, which is safe becauseKeyedAgentChatPagerenders not-found whenagentIdis empty).Precision (hand-verified by two read-only agents on the pre-fix report):
ParsedMessageEntry.mergedFrom, omitted in an untyped literal) is caught bytscwhen narrowing.Current dead slots, excluding
idiomatic(options bags,signal, param defaults) and the skip list (chatFamilyAllowsArchive/chatStatusAllowsArchivedocumented fail-open,fileContentOptions,aiGatewayDisabled,CompactIntegerField.error/disabled,mergedFrom): 254 slots in 69 files (about 110 data, 73 callback, 70 flag). Well over the one-PR threshold, so one PR per cluster.6. Clusters (one PR each, separate branches from
main)useChatStore,chatStore,rightPanelTabStorage,sidebarTabStorage,useChatDraftAttachments,chatDraftAttachmentStorage,useConversationEditingState,useChatToolInvalidations,useWorkspaceWatch,useGitWatcher,chatQueueReconciliation. Reference PR, done by me.ConversationTimeline,MessageBlocks,UserMessageContent,AttachmentBlocks,AssistantOutput,messageHelpers,ChatStatusCallout,ChatElements/tools/*.AgentChatInput,ChatMessageInput,SkillsTriggerMenu,AttachmentPreview,ChatPageContent,AgentChatPageView.ChatsSidebar/*,ChatSummary,ChatActionsMenuItems(flags only).DiffViewer/*,GitPanel,TerminalPanel,DesktopPanel,RightPanelAddTabControl,DebugPanel/*.UserCompactionThresholdSettings,WebPushButton,ChimeButton,AgentSetupNotice,CompactOrgSelector,UsageIndicator,modelOptions,diffColors,useAgentsPageKeybindings.Rules for every cluster:
tscis the source of truth for what to update.disabled/error.7. Open questions
None.
This PR was generated by Coder Agents on behalf of @DanielleMaywood.