Skip to content

feat(server): show Kimi For Coding plan limits for Claude instances - #8485

Closed
BarretoDiego wants to merge 85 commits into
pingdotgg:mainfrom
BarretoDiego:feat/claude-kimi-rate-limits
Closed

BarretoDiego wants to merge 85 commits into
pingdotgg:mainfrom
BarretoDiego:feat/claude-kimi-rate-limits

Conversation

@BarretoDiego

@BarretoDiego BarretoDiego commented Aug 28, 2026 •

Copy link
Copy Markdown

Problem

Claude Code instances pointed at the Kimi For Coding endpoint (ANTHROPIC_BASE_URL=https://api.kimi.com/coding/) never appear in the sidebar plan-limits meter: that backend emits no rate_limit_event messages, and the Claude SDK's get_usage control API reports rate_limits_available: false for non-Anthropic backends.

How

  • New provider/kimiCodeUsage.ts: detects a Kimi-backed instance from its resolved environment (api.kimi.com / api.kimi.ai, or the KIMI_CODE_BASE_URL override the Kimi CLI honors), fetches GET {base}/coding/v1/usages with the instance's own key, and normalizes the payload into provider-agnostic windows: the rolling 5-hour window, the weekly quota, and the Extra Usage wallet (plus the membership tier as the plan label).
  • ClaudeAdapter reads this endpoint after every turn and on manual refresh. Unlike the Anthropic path, a Kimi-backed refresh needs no active session.

Verification

  • 12 new tests (parser + adapter refresh without session / post-turn event / 401); full ClaudeAdapter suite green (93 tests).
  • Ran against a live Kimi For Coding account through a dev server: the instance appears in the meter as Advanced · 5-hour 64% · Weekly 33%, matching the Kimi console.

Model: kimi-for-coding/k3-256k · Harness: opencode


Note

Medium Risk
Changes provider session lifecycle (instance switches), orchestration reactors, and persisted provider snapshots; incorrect limit data or cache hydration could mislead users but does not alter billing or core auth.

Overview
Adds end-to-end plan limit tracking for Codex, Claude, and Kimi For Coding: adapters normalize provider-specific usage into shared ProviderRateLimits snapshots, emit account.rate-limits.updated on the runtime stream, and expose refreshRateLimits for on-demand reads (Claude SDK usage, Codex account/rateLimits/read, Kimi /v1/usages without a session).

On the server, a new ProviderRateLimitsReactor persists observations via ProviderRegistry.setProviderRateLimits (sparse merge vs authoritative replace), survives restarts in the provider status cache, and clears stale limits when an instance is rebuilt or the account home changes. Clients can call server.refreshProviderRateLimits to force a refresh and update subscribed provider snapshots.

Mobile Usage gains a Plan limits section (progress bars, reset countdowns, manual refresh). Settings and sidebar-related client prefs (grouping, pinned rate-limit keys) are extended in tests/contracts. ProviderCommandReactor now stops the old session when switching provider instances before starting the new one.

Docs: README links to Track plan limits user guide.

Reviewed by Cursor Bugbot for commit e0968af. Bugbot is set up for automated code reviews on this repo. Configure here.

Note

Add provider plan-rate-limits tracking, sidebar grouping overhaul, and multi-pane thread workspace

  • Introduces ProviderRateLimits schemas in contracts, with normalization helpers for Claude, Codex, and Kimi For Coding usage payloads. Adapters emit account.rate-limits.updated runtime events with normalized snapshots and expose refreshRateLimits.
  • Adds ProviderRateLimitsReactor which listens to runtime events and persists snapshots into ProviderRegistry via setProviderRateLimits (merge or replace). Rate-limit observations survive restarts via cache seeding and are cleared on instance rebuilds.
  • Adds a serverRefreshProviderRateLimits WS RPC (requires orchestration operate scope) that refreshes limits for a specific provider instance and returns updated providers.
  • Overhauls the web sidebar with configurable primary/secondary grouping (environment/project/provider), provider filtering, section drag-and-drop reordering, per-section settled pagination, attention chips, and compact thread rows. Removes the old project-scoping dropdown.
  • Introduces a multi-pane ThreadWorkspace UI with draggable tabs/panes, selectable layouts, shared diff worker pool, and persistent named workspaces. Server and draft thread routes now render ThreadWorkspace instead of ChatView.
  • Adds live markdown highlighting in the prompt composer via a new Lexical scanner and transform pipeline, with CSS classes for styled spans.
  • Adds environment-scoped and project-scoped pages with breadcrumbs (EnvironmentCrumb, ProjectCrumb).
  • Adds a sidebar rate-limits meter, pinned rate-limits dock, and a mobile plan-limits section with refresh support.
  • Risk: ChatHeader removes the onNewThreadInProject prop and now requires activeProjectId; ServerProvider schema gains optional rateLimits and rateLimitsRefresh fields. AccountRateLimitsUpdatedPayload gains optional snapshot and updateMode fields — existing consumers that decode these events must tolerate the new fields. providerStatusCache.isCachedProviderCorrelated now requires matching continuation.groupKey, which may cause previously-correlated cached providers to fall back to fresh data if group keys diverge.
📊 Macroscope summarized e0968af. 74 files reviewed, 27 issues evaluated, 9 issues filtered, 15 comments posted

🗂️ Filtered Issues

apps/server/src/provider/Layers/ClaudeProvider.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 53: CLAUDE_PRESENTATION advertises rateLimitsRefresh: "active-session-required" for every Claude instance, but the same adapter's refreshRateLimits explicitly detects Kimi-backed instances and fetches their standalone usage endpoint without a session. This metadata tells consumers that the refresh requires a live protocol connection, so a Kimi instance is incorrectly presented/handled as requiring an active session even though its supported manual refresh works without one. [ Out of scope (triage) ]
apps/server/src/provider/Layers/ProviderRegistry.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 486: setProviderRateLimits inserts the observation into rateLimitsRef before determining whether instanceId currently exists. If a late runtime event or in-flight manual refresh arrives after an instance was removed, the map retains its limits even though no provider is updated. When a new instance with that same id is subsequently added, syncLiveSources does not delete the entry (there is no previousSubs entry for it), and applyProviderRateLimits attaches the old account's limits to the new instance. [ Already posted ]
apps/web/src/components/Sidebar.tsx — 3 comments posted, 6 evaluated, 3 filtered
  • line 2465: sectionsOwnSettled treats a stale secondary "project" axis as active even when the primary axis is "none". Selecting Nothing after previously choosing project grouping leaves threadSecondaryGrouping unchanged, buildSidebarThreadGroups returns no groups for the none primary axis, and the global settled shelf is suppressed; consequently all settled threads disappear from the sidebar. [ Cross-file consolidated ]
  • line 2467: hasEnvironmentSections also considers the secondary axis when the primary grouping is "none". After changing a previously nested environment grouping to Nothing, the secondary value remains "environment", but no groups are built; this hides the only New project control whenever threads already exist, since there are no environment headers to provide its replacement action. [ Cross-file consolidated ]
  • line 3397: The bulk-action set claims to retain only rendered rows but filters against threadByKeyRef, whose threadByKey includes every activeThreads entry even when its group is collapsed. A user can select a thread, collapse its section, select a visible row and choose bulk Delete; the hidden selected thread is included in the confirmed deletion and its conversation is permanently removed. [ Already posted ]
apps/web/src/components/scope/EnvironmentScopePage.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 158: The settled label is derived from threadCount - activeThreadCount, but threadCount also includes threads placed in the snoozed shelf. A project whose only thread is currently snoozed therefore renders e.g. 1 settled, even though the same shelving rules classify that thread as Snoozed; projects with active and snoozed threads also silently omit the snoozed work from this status. [ Out of scope (post-validation triage) ]
apps/web/src/components/sidebar/SidebarGroupingBar.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 219: Selecting Nothing (flat list) only updates sidebarThreadPrimaryGrouping and leaves a previously selected secondary axis intact. For example, after grouping by Environment then Project, choosing Nothing leaves secondaryAxis === "project"; buildSidebarThreadGroups ignores it because the primary is none, but the sidebar's sectionsOwnSettled still sees it and suppresses the global settled shelf. Consequently all settled threads disappear from the flat sidebar until the secondary setting is changed elsewhere. [ Cross-file consolidated ]
apps/web/src/components/sidebarThreadGrouping.ts — 2 comments posted, 4 evaluated, 1 filtered
  • line 181: providerDriverLabel produces a different driver-section/filter label for the same driver depending on which instance is encountered first. For example, the built-in claudeAgent entry is named Claude, but a custom claudeAgent instance returns ClaudeAgent here; since deriveSidebarProviderOptions and bucketing retain the first identity, a list containing both can show ClaudeAgent or Claude solely based on thread order rather than a stable driver label. [ Out of scope (post-validation triage) ]
apps/web/src/threadWorkspaceStore.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 479: normalizeThreadWorkspaceModel can still produce duplicate pane ids for malformed persisted data. While parsing a duplicate thread-pane-N, it calls createPane() before reservePaneSequence(parsedPanes) advances the generator; if the generated sequence equals the retained id (for example two persisted thread-pane-2 entries after initial pane creation), both panes retain thread-pane-2. Subsequent pane activation/tab operations then apply to both panes rather than repairing the required unique-id invariant. [ Out of scope (post-validation triage) ]

BarretoDiego and others added 30 commits August 21, 2026 15:10
The sidebar inbox is one flat list. With several environments, projects
and providers in play there is no way to see "just this machine" or
"just Codex" without scoping to a single project at a time, and every
card repeats the project name whether or not that is the useful bit.

Adds a compact bar under the project selector with three menus:

- Group by: environment, project or provider, plus an optional second
  axis nested inside the first. "Nothing" keeps today's flat list and
  stays the default.
- Provider filter: narrows every shelf, not just the inbox, so the
  filter never lies about what "only Claude" means.
- Sort: last activity or date created. The existing project grouping
  mode (repository / folder / project) is surfaced here too, instead of
  living only in Settings.

Each trigger reads out its current choice, so the bar doubles as the
readout of how the list is arranged.

Grouped rows say each thing once: a card drops whatever a section header
above it already states, so the same row is three lines in the flat list
and one line under a project header. Collapsed sections carry an
attention rollup — approvals, input requests, failures, unread
completions and running work — using the same status rules the rows
themselves follow, so a header can never claim something its rows would
not show. Unread finished threads get a dot next to their title.

The grouping itself is pure and unit-tested: sections come out in
first-appearance order and threads keep their incoming order, so sorting
and grouping stay orthogonal. Collapse state persists per section key
and resets when the axes change, so stale keys cannot pre-collapse
unrelated sections. Pinned keeps its manual order and the snoozed and
settled shelves stay whole.

Written by Claude Opus 5 in Claude Code.
Grouping the inbox by project surfaces every project as a header, but
starting work in one still meant going back up to the project selector
and changing scope.

Adds a New thread button beside the collapse arrow on project section
headers. Environment and provider sections span several projects, so
they have no unambiguous target and get no button rather than a guess.

The button is a sibling of the toggle rather than a child (a button
inside a button is invalid), and it reads its target off the section's
first thread instead of parsing the group key, so ids stay branded and
the key format stays an implementation detail.

Written by Claude Opus 5 in Claude Code.
feat(web): agrupamento, filtro e ordenação da sidebar
- Corrige backend salvo diretamente que ocultava seu ambiente T3 Connect (pingdotgg#7086), ajustando `environmentSections` e o `useConnectionController`
- Corrige queries de busca de thread grandes demais que derrubavam os clients (pingdotgg#6633), em `threadSearch` no `client-runtime`
- Adiciona cobertura de testes para os dois casos: `environmentSections.test.ts`, `threadSearch.test.ts` e `DesktopClientSettings.test.ts`
- 2 commits do upstream, 6 arquivos alterados (+114/-15), sem conflitos com as modificações do fork

Sync automatico t3code-sync em 2026-08-22T00:08:13-03:00
…eads

- Analytics: threads e turns passam a registrar qual cliente os iniciou, com novos campos nos contratos de orchestration e baseSchemas (pingdotgg#7774)
- Servidor: SessionStore e persistence/AuthSessions ganham rastreio da conexão do cliente, com nova migration 041_AuthSessionClientConnection
- WebSocket (ws.ts) e OrchestrationEngine (Layers/Services) propagam a informação de cliente ao criar threads e turns
- Client-runtime: authorization (remote/service) e connection/resolver atualizados para expor os metadados do cliente
- Mobile e web: platform.ts e authClientMetadata.ts ajustados para informar a plataforma de origem
- Cobertura de testes ampliada em server.test.ts, SessionStore.test.ts, OrchestrationEngine.test.ts, connection.test.ts e resolver.test.ts

Sync automatico t3code-sync em 2026-08-22T03:03:04-03:00
…ktop

- Chat/markdown: renderização de imagens do workspace no ChatMarkdown (novo módulo markdownImages no client-runtime), correção de links de pasta com espaço no command-click e tratamento de marcadores largos em listas ordenadas.
- Timeline de mensagens: mensagens de follow-up param de ser empurradas para o topo e execuções mistas de ferramentas deixam de ser marcadas como falha.
- Web: rótulos de service tier do Codex ficam legíveis, com ajustes no TraitsPicker, ChatView e index.css.
- Desktop/rede: falhas ao subir o Tailscale não quebram mais os endpoints anunciados e o PATH do usuário é restaurado em servidores remotos via SSH.
- Server/providers: ajustes em CodexAdapter, ClaudeProvider, CodexProvider e ActivityPayloadProjection, com novos testes de registry e projeção.
- Mobile: melhorias no ThreadFeed/ThreadDetailScreen com live-follow e suporte a SelectableMarkdownText.
- Testes: remoção de asserção redundante de release note no desktop e ampla adição de cobertura nos pacotes tocados.
- Merge sem conflitos: 9 commits do upstream integrados, mantendo intactas as modificações próprias do fork.

Sync automatico t3code-sync em 2026-08-22T18:02:07-03:00
Adding a project always started by asking which environment to add it to,
even when the caller already knew. The sidebar is about to ask from an
environment section header, where re-asking would be the palette ignoring
where the click came from.

The open detail and the palette's open intent carry an optional
environmentId. When it is set, the flow skips straight to browsing sources
in that environment; when it is absent the picker behaves exactly as before.
The key is absent rather than undefined so the two cases stay
distinguishable under exactOptionalPropertyTypes.

Written by Claude Opus 5 in Claude Code.
The project selector was doing three unrelated jobs at once: it scoped the
whole sidebar to one project, it was the only route to project settings, and
it took a row of sidebar width to say the name of a project the list below
already showed. Meanwhile the list itself could only show projects that
happened to have threads, so a quiet project was unreachable and a finished
one disappeared into a single Settled shelf shared by everything.

The selector is gone. A project is a section, and the section header carries
what you can do with it:

- Project sections get New thread and Project settings.
- Environment sections get New project, pointed at that environment.
- Provider sections span projects and environments, so they get nothing
  rather than a guess.

Actions read off the section's target rather than off its first thread,
because sections now exist before they have threads: every known project
seeds one. The collapse arrow is always the last item, so it stays a fixed
landmark while hover-only actions come and go around it. It is a sibling
button (a button inside a button is invalid) and stays out of the a11y tree,
since the labelled header button already exposes the same action.

Settled threads follow the same idea. Grouped by project, each section ends
with its own Settled shelf, closed by default with a count and a Show more
tail; the global shelf only renders when no section owns history, so nothing
is ever listed twice. Expansion is component state on purpose: an archive is
opened to answer one question, and restoring six unrolled histories on
startup would bury the work.

The default grouping becomes environment then project. The actions above
live on section headers, so shipping with a flat list would ship a sidebar
with nowhere to put them.

Scoping goes away with the selector. It had no other entry point, so the
state, the thread filter and the draft filter go with it.

Mobile keeps its own project filter in its own navigation; this is the web
and desktop sidebar only.

Written by Claude Opus 5 in Claude Code.
feat(web): make sidebar sections the place you act on projects
Two things the first pass got wrong, both visible the moment the sidebar
actually ran.

The header actions were hover-only, carried over from when New thread was a
nicety next to a project selector that already did the job. The selector is
gone: these buttons are now the way into a project, and an action you have
to hunt for by hovering is an action most people never find. They stay
visible, muted, and brighten on hover.

Settled rows ignored their indentation. The slim variant — the shape settled
and snoozed rows use — has its own `<li>` that never applied `indentDepth`,
so a settled thread inside a project section sat flush against the sidebar
edge as if it belonged to no one, while its own Settled header was indented
under the project. It now indents and draws the same guides as every other
row, which also fixes snoozed rows for whenever they end up nested.

Written by Claude Opus 5 in Claude Code.
fix(web): show section actions and indent settled rows
Every project has a row now, but no way to get rid of one from there. The
action existed only in LegacySidebar, which the new sidebar replaced.

Right-clicking a section header opens its actions as a menu: New thread and
Project settings for a project, New project for an environment, and — only
for a project — Remove project.

Removing deliberately does not get an icon next to New thread. It is the one
destructive thing a section header can do, and a third button one slip away
from the two you press all day is how people delete a project by accident.
The context menu is also the gesture threads already use for their own
Archive and Delete, so this is the pattern the sidebar already teaches.

The confirmation names the path, the environment and how many threads go
with the project; a project that still has threads needs force, and says so.
Drafts parked in the removed project are cleared, or the sidebar would keep
a row pointing at a project that no longer exists.

Written by Claude Opus 5 in Claude Code.
feat(web): remove a project from its sidebar section
…ntraste

- Mobile: preserva dimensões de imagens em markdown no ThreadFeed, com novo helper markdownImageSize e testes de threadActivity
- Server: CodexAdapter deixa de manter threads do Codex concluídas presas em "working"
- Web: novo controle de contraste na aparência (appearanceContrast, SettingsPanels, settingsSearch, contracts/settings) refletido em index.css, tema de anotações e clerkAppearance
- Web/clients: respostas em abertura continuam visíveis após o fim dos turnos (MessagesTimeline.logic, contextMenuFallback)
- Ajustes de consistência de UI em componentes compartilhados (button, ModelPicker, ChangedFilesTree, FileBrowserPanel, color-selector) e doc .macroscope/check-run-agents/ui-consistency.md
- 4 commits do upstream integrados sem conflitos; modificações próprias do fork preservadas

Sync automatico t3code-sync em 2026-08-22T21:02:04-03:00
- Servidor passa a usar a branch default do remote em vez de assumir `main`, com ajustes em GitManager e nos drivers de VCS (GitVcsDriver/GitVcsDriverCore)
- Cobertura de teste adicionada para o novo fallback de branch default em GitManager.test.ts
- Web: removida a duplicação do progresso de atualização de provider, simplificando ProviderUpdatePrimaryNotification
- Ajuste da lógica de ProviderUpdateLaunchNotification acompanhado de novos testes
- Merge sem conflitos: 2 commits do upstream integrados, mantendo intactas as modificações próprias do fork

Sync automatico t3code-sync em 2026-08-23T00:02:03-03:00
- 2 commits trazidos de upstream/main
- 0 arquivo(s) em conflito
- verificacao: pass

Sync automatico t3code-sync em 2026-08-23T00:02:43-03:00
- Redesign das skills nos menus `$` e `/` do composer, com ajustes de busca de slash commands e padding das linhas do menu de projetos na sidebar
- Correções na área de chat: banners de update do servidor alinhados ao composer, toggle do painel direito voltando a responder no desktop, e tool calls não deixando mais a thread em branco
- Ajustes em work logs: reuso de linhas durante o streaming (perf) e falhas de tool já recuperadas deixando de marcar o log como vermelho
- Correções em clients/server: threads fixadas resolvidas indo para a seção settled, reconexão após falha de credenciais em updates remotos e kills não deixando trabalho do Claude pendurado
- Nova feature no Codex: envio de feedback de thread para a OpenAI (threadFeedback no client-runtime, contratos de RPC/provider e settings)
- Isolamento das requisições de imagem no markdown do mobile
- CI/release: builds de release e empacotamento no Windows mais rápidos, e Macroscope voltando a aprovar pull requests
- 1 arquivo conflitou durante o merge; conflito resolvido manualmente preservando as modificações do fork e incorporando as mudanças do upstream

Sync automatico t3code-sync em 2026-08-23T18:06:41-03:00
- Desktop: notas de release seguem visíveis durante o download da atualização (SidebarUpdatePill).
- Web: URLs configuradas com esquema em maiúsculas passam a ser tratadas como seguras (environments/primary/target.ts).
- Web: badge de provider fica legível em temas escuros (ProviderInstanceIcon).
- Cobertura de testes: novos casos em environments/primary/bootstrap.test.ts para o tratamento de esquemas.
- 3 commits do upstream integrados sem conflitos; modificações próprias do fork preservadas.

Sync automatico t3code-sync em 2026-08-23T21:01:35-03:00
Section order was whatever the grouping produced: sections with live work
first, then history-only ones, then the quiet seeded projects, first
appearance breaking ties inside each rank. That is a reasonable default and a
poor permanent arrangement — the one project you check every morning drifts
down the list the moment nothing is running in it, and environments had no
ordering control at all.

Order becomes a second pass over the built tree rather than a variant of the
grouping. Which sections exist is one question; where they sit is another, and
splitting them is what lets an arrangement survive threads arriving, settling,
and being filtered out. Three modes, in the same menu that already sorts
threads: Busiest first (the old behavior), Name (A–Z), and Custom.

Custom is reachable two ways, because a sidebar is a list you point at and
also a list you drive from the keyboard. Drag a header to move it, or
right-click and choose Move up / Move down; either switches to Custom and
records the whole level, so the result stops depending on activity. Requiring
the mode to be picked first would have made the first drag a silent no-op.

Sections move only within their own level. A drop is refused outright when it
lands outside the dragged section's siblings, and while a drag is in flight
every other level disables its droppables, so a project level never animates a
swap it would then discard. Reparenting is not a thing sections can express.

Header rows now carry their parent, their siblings and their index. The
alternative was recovering the level by splitting keys on "/", which happens to
work today and would break the first time an id contains one.

The manual list is one flat array across levels — child keys are already
parent-prefixed, so ranks are unambiguous — and keys of sections that are not
currently rendered are kept rather than pruned: grouping axes and the provider
filter hide sections temporarily, and dropping their order would quietly throw
away an arrangement. Switching to Custom from the menu seeds every unplaced
section where it currently sits, so it freezes what you are looking at instead
of leaving untouched levels free to reshuffle. A project added later joins the
end of its level; Reset section order goes back to Busiest first.

Written by Claude Opus 5 in Claude Code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rary — try again in a moment. If it persists, check https://status.claude.com.

Sync automatico t3code-sync em 2026-08-24T03:05:43-03:00
feat(web): let the sidebar's sections be arranged by hand
The header above a thread showed a project name and a title. The project was
not a link — clicking it started a new thread, an action a breadcrumb has no
business performing — and the environment was missing entirely, so with two
servers connected the header never said which machine the work was running on.
There was also nowhere to go: no view of one environment's projects, and no
view of one project's threads outside the sidebar's narrow column.

The header now reads environment / project / thread, widest scope first, and
every crumb above the thread is a link to that scope's own page. The
environment leads whenever the server actually names itself; a blank name
renders no crumb rather than an icon with nothing beside it.

Two pages back those links. The environment page lists every project on that
server, busiest first, with each one's live thread count and last activity —
including projects with no threads yet, the same promise the sidebar's seeded
sections make. The project page lists that project's threads under Active,
Snoozed and Settled.

Those shelves are the sidebar's rule, reused rather than re-derived, so the two
surfaces cannot disagree about what is finished. One deliberate omission: the
sidebar's pull-request snapshot stays behind. It is a sidebar-local cache of
open PRs, and a page that needed one would be fetching PR state to decide where
a row goes. With Auto-settle merged threads on, a thread whose PR just merged
reads as active here until the server stamps it.

The project page is scoped to the project on *this* environment rather than to
the sidebar's logical grouping. The crumb comes from a thread, a thread has
exactly one environment, and a page reached by following a path should not
quietly widen it.

Clicking the project name no longer starts a thread. Both pages carry a New
thread / New project button, the sidebar's project headers still have theirs,
and the keybinding is untouched — so the action loses a hiding place, not a
home.

Docs: the new section in the thread sidebar guide. Desktop inherits this from
web; mobile has its own navigation and no header of this shape, so it is
unaffected.

Written by Claude Opus 5 in Claude Code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
feat(web): make a thread's path in the header navigable
- Servidor: correções em worktrees (recriação antes do turn, delete sem falhar em worktree removida, checkout de submódulos), recuperação de falha ao interromper provider, execução da CLI em Node sem import.meta.main, auto-accept edits no OpenCode e limite na descoberta de skills.
- Web/composer: upload de anexos antes do envio, avisos de update não vazam mais pelo composer, follow-ups sem espaço em branco gigante e comparação de versão cliente/servidor via semver.
- Pull requests: leituras live sempre atualizadas e badges de PR merged preservados após deleção de branch.
- Mobile: primeira thread abre acima do composer no Android, controles de thread restaurados em tablets Android e estado de colapso da shelf persistido.
- UI/Codex: agrupamento da sidebar de terminal mais claro e prompts de aprovação de acesso do app no Codex.
- Infra/manutenção: vouch de contribuidores recorrentes, deploys automáticos da Vercel desativados em PRs de marketing e patch do @legendapp/list.
- Conflito: 1 arquivo conflitou, resolvido mantendo as modificações do fork e incorporando as mudanças do upstream.

Sync automatico t3code-sync em 2026-08-24T14:20:33-03:00
Providers meter subscription plans on rolling windows — Claude's 5-hour and
weekly windows, Codex's primary/secondary pair, plus spend and credit ceilings —
and T3 Code never surfaced any of it. You found out you were out of headroom by
getting rate limited mid-turn.

Adapters now normalize their native payload into one provider-agnostic shape, a
queue-backed reactor records each observation onto the provider snapshot clients
already subscribe to, and the per-instance status cache carries the last
observation across restarts. The sidebar footer gets a gauge next to Settings,
Pull Requests and Usage: the ring fills to the most constrained live window
across every provider and environment, and its popover breaks down each
provider, plan, window, and time left. A window whose reset instant has passed
renders as reset instead of repeating a spent number.

Providers only report while they run, so the meter is explicit about having no
data yet rather than implying zero usage.

Model: claude-opus-5[1m] · Harness: T3 Code (Claude Code)
feat(web): show provider plan limits in the sidebar
fix(usage): report limits per provider account
Sync automatico t3code-sync em 2026-08-24T18:02:22-03:00
…rkspace

The thread workspace could only split into 2 or 3 columns, so a wide display
had no way to watch four agents side by side, and tab drag-and-drop gave no
indication that a pane was a valid drop target beyond a thin ring once the
cursor was already over it.

Adds a `four-columns` layout alongside the existing geometries, and renders a
drop hint in every pane while a thread tab is being dragged. The hint stays
mounted and only animates opacity, so idle panes never repaint; the pane under
the cursor swaps to a primary-tinted border and a "release" label.

Model: Claude Opus 5 via Claude Code
…hint

feat(web): add 4-column layout and drop-target hints to the thread workspace
The prompt composer rendered every character the same, so a pasted code
fence or an inline `snippet` was indistinguishable from prose until the
message was sent.

Paint markdown syntax live using Lexical text formats on the composer's
own text nodes rather than an overlay, so the highlight shares a layout
pass with the existing mention and skill chips instead of competing with
them for position. Node text is never rewritten: the submitted prompt is
byte-identical to what was typed.

Covers fenced blocks (including half-typed ones), inline code, bold,
italic, strikethrough, headings, quotes, lists, thematic breaks, and
links. Delimiters are dimmed rather than hidden. Chips are opaque to the
scanner so a path like @src/_a_/b.ts cannot read as emphasis, and the
scan is skipped past 20k characters to keep large pastes cheap.
…hting

feat(web): highlight markdown syntax while typing in the composer
- Adiciona revelação de chips de arquivo do chat no gerenciador de arquivos do sistema (pingdotgg#7140), com suporte no launcher externo do servidor (apps/server/src/process/externalLauncher.ts) e novo canal em ws.ts
- Estende ChatMarkdown no web para renderizar e acionar os chips de arquivo, junto com ajustes no OpenInPicker e em remoteOpen.ts
- Acrescenta rótulos de editor e de explorador de arquivos (editorLabels.ts, preview/fileExplorerLabel.ts) e amplia os contratos em packages/contracts (editor.ts, server.ts)
- Ajusta os componentes de pull request (Markdown, editor, anotação de review, abas de summary e timeline) e o index.css
- Amplia cobertura de testes no servidor e no web (~648 linhas em externalLauncher.test.ts, além de server.test.ts, ChatMarkdown.test.tsx e testes de labels)
- Inclui nota de consistência de UI em .macroscope/check-run-agents/ui-consistency.md
- Conflito em 1 arquivo, resolvido mantendo as modificações do fork e reaplicando as mudanças do upstream por cima

Sync automatico t3code-sync em 2026-08-25T18:09:46-03:00
…d ones

The workspace threw away everything but its geometry on reload. Open tabs were
rebuilt from whichever thread the URL happened to name, so stopping work meant
reopening every pane by hand. That was a deliberate trade at the time: nothing
could tell a deleted thread apart from one that had simply not synced yet, so
persisting tabs risked restoring dead ones.

Persists the whole workspace — layout, the tabs in each pane, and the selected
thread — and resolves the staleness problem with a prune pass instead of by
discarding state. A tab is only dropped once the environment that owns it has
actually delivered a snapshot and did not report the thread; an environment
that is offline, still syncing, or not yet in the catalog keeps its tabs, and
the routed tab is never dropped because the router needs one to represent.
Everything read out of storage goes through a repair pass, so a truncated or
hand-edited entry degrades to a usable workspace rather than crashing one.

On top of the automatic restore, the layout menu can now save the current
workspace under a name and restore it later. Snapshots store panes by position
and mint fresh pane ids on restore, so restoring one twice cannot alias a live
pane.

The prune pass is gated on a signature of what actually decides its outcome.
Its two inputs churn on ordinary thread traffic, and pruning on each of those
would write the persisted workspace to storage on every incoming message.

Model: Claude Opus 5 via Claude Code
feat(web): restore the thread workspace across restarts and save named ones
- Corrige o push do driver de VCS: commits de uma feature branch não são mais gravados na branch base (pingdotgg#8228)
- Ajustes em `apps/server/src/vcs/GitVcsDriverCore.ts` com a lógica de push corrigida
- Adiciona cobertura de testes em `GitVcsDriverCore.test.ts` para o cenário de branch base
- Sincronização diária automática com a branch de nightlies do upstream pingdotgg/t3code (1 commit)
- Merge sem conflitos: nenhuma modificação própria do fork precisou de resolução manual

Sync automatico t3code-sync em 2026-08-25T21:02:23-03:00
- Corrige `push` no servidor: commits de uma feature branch nao sao mais gravados na branch base (upstream pingdotgg#8228)
- Ajustes em `apps/server/src/vcs/GitVcsDriverCore.ts` com a logica de protecao da branch base
- Adiciona cobertura de testes em `GitVcsDriverCore.test.ts` para o novo comportamento
- Sync sem conflitos: 1 commit do upstream integrado, modificacoes do fork preservadas

Sync automatico t3code-sync em 2026-08-25T21:03:34-03:00
- Adiciona ModelManifest (ModelManifest.ts, model-manifest.json e testes) para buscar a classificação de modelos legados a partir de um manifesto hospedado
- Ajusta ClaudeDriver e CodexDriver, além de ClaudeProvider e CodexProvider, para consumir a classificação vinda do manifesto em vez da lógica local
- Atualiza testes de provider (ClaudeCapabilitiesProbe, CodexProvider, ProviderInstanceRegistryLive, ProviderRegistry) e a inicialização em server.ts
- Sobe @clerk/electron para 0.0.37, com reflexos em pnpm-lock.yaml e pnpm-workspace.yaml
- Documenta as mudanças em docs/internals/glossary.md e docs/internals/providers.md
- Merge automático de 2 commits do upstream sem conflitos; nenhuma modificação própria do fork precisou de resolução manual

Sync automatico t3code-sync em 2026-08-26T00:02:29-03:00
- Correção no desktop para que a UI do Clerk receba os fixes estáveis de autenticação (pingdotgg#8248)
- Remoção de 6 linhas em apps/web/src/main.tsx como parte desse ajuste
- Preparação do release v0.0.34, com bump de versão nos package.json de desktop, server, web e contracts
- Merge sem conflitos: nenhum arquivo conflitou e as modificações próprias do fork foram preservadas

Sync automatico t3code-sync em 2026-08-26T03:02:22-03:00
…o de threads

- CI: workflow de release (.github/workflows/release.yml) otimizado, cortando cerca de um minuto de cada release
- Threads não-settled voltam ao topo da lista: correção de ordenação propagada por servidor, web e mobile
- Servidor: rastreamento de `unsettledAt` no projector, ProjectionPipeline, ProjectionSnapshotQuery e ProjectionThreads, com nova migration 043_ProjectionThreadsUnsettledAt
- Web e client-runtime: ajustes em Sidebar.logic, threadSort e threadReducer para refletir a nova ordenação
- Contratos: novo campo em packages/contracts/src/orchestration.ts para expor o estado de settled
- Testes: cobertura adicional para decider/projector settled, pipeline de projeção, Sidebar.logic e threadListV2
- Docs: docs/user/thread-sidebar.md atualizado com o novo comportamento da barra lateral
- Merge sem conflitos (0 arquivos conflitantes); modificações do fork preservadas integralmente

Sync automatico t3code-sync em 2026-08-26T06:03:24-03:00
Replace exhausted provider percentages with a real-time reset countdown across web, desktop, and mobile.
…Code · Use an Anthropic API key instead, or ask your admin to enable access

Sync automatico t3code-sync em 2026-08-27T00:01:16-03:00
…Code · Use an Anthropic API key instead, or ask your admin to enable access

Sync automatico t3code-sync em 2026-08-27T03:03:17-03:00
…Code · Use an Anthropic API key instead, or ask your admin to enable access

Sync automatico t3code-sync em 2026-08-27T06:02:19-03:00
…Code · Use an Anthropic API key instead, or ask your admin to enable access

Sync automatico t3code-sync em 2026-08-27T10:04:49-03:00
Claude Code instances pointed at the Kimi For Coding endpoint
(ANTHROPIC_BASE_URL=api.kimi.com/coding/) never emit rate_limit_event
messages, and the SDK usage API reports rate_limits_available: false for
third-party backends, so the sidebar rate-limits meter had nothing to
show for them.

The adapter now detects a Kimi-backed instance from its environment and
reads plan usage from Kimi's own account endpoint (GET
{base}/coding/v1/usages) instead: the 5-hour rolling window, the weekly
quota, and the Extra Usage wallet become normal provider rate-limit
windows. The read happens after every turn and on manual refresh — and
unlike the Anthropic path, the manual refresh needs no active session.

Model: kimi-for-coding/k3-256k · Harness: opencode
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 419a5182-cf80-4984-a9d7-bd763c11c936

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added vouch:unvouched Author is not yet trusted in the VOUCHED list. size:XXL 1,000+ changed lines (additions + deletions). labels Aug 28, 2026
@BarretoDiego

Copy link
Copy Markdown
Author

Closing: opened against upstream by mistake — this targets my fork's main first. May resubmit through the proper proposal process later.

@macroscopeapp macroscopeapp Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the Effect service changes in this PR (new ProviderRateLimitsReactor, the Kimi usage module, and the adapter/registry/service surface additions). Two convention violations in newly added code:

  • The new ProviderRateLimitsReactor service is defined as a Services/ tag + standalone …Shape interface + Layers/ …Live layer, instead of one canonical module with the interface inline in Context.Service and export const layer.
  • KimiCodeUsageFetchError stores a free-form message as its only real attribute and drops the underlying failure.

Everything else (dependency acquisition via yield* ProviderService / yield* ProviderRegistry, no runtime boundaries introduced in service construction, subpath namespace imports) looks consistent with the conventions.

Posted via Macroscope — Effect Service Conventions

} satisfies ProviderRateLimitsReactorShape;
});

export const ProviderRateLimitsReactorLive = Layer.effect(ProviderRateLimitsReactor, make);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The canonical layer for a new service should be exported as layer from the service's single module, not as a …Live alias in a separate Layers/ file. Once the tag, make, and layer live in apps/server/src/orchestration/ProviderRateLimitsReactor.ts, this becomes:

Suggested change
export const ProviderRateLimitsReactorLive = Layer.effect(ProviderRateLimitsReactor, make);
export const layer = Layer.effect(ProviderRateLimitsReactor, make);

Call sites (server.ts, OrchestrationEngineHarness, tests) should be updated mechanically to ProviderRateLimitsReactor.layer.

Posted via Macroscope — Effect Service Conventions

Comment on lines +14 to +29
export interface ProviderRateLimitsReactorShape {
/**
* Start forwarding `account.rate-limits.updated` observations into the
* provider registry. Must be run in a scope so the worker is finalized on
* shutdown.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;

/** Resolves once every observed event has been applied. Test seam. */
readonly drain: Effect.Effect<void>;
}

export class ProviderRateLimitsReactor extends Context.Service<
ProviderRateLimitsReactor,
ProviderRateLimitsReactorShape
>()("t3/orchestration/Services/ProviderRateLimitsReactor") {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is a newly created service with a single implementation, so it should follow the canonical single-module shape rather than the Services/ + Layers/ split: hoist it to apps/server/src/orchestration/ProviderRateLimitsReactor.ts in the order imports → Context.Service tag → make → layer, and define the interface inline in the tag instead of keeping a standalone ProviderRateLimitsReactorShape.

Consumers that currently annotate against the shape (ProviderRateLimitsReactorShape["start"], satisfies ProviderRateLimitsReactorShape) would then refer to ProviderRateLimitsReactor["Service"].

-export interface ProviderRateLimitsReactorShape {
-  readonly start: () => Effect.Effect<void, never, Scope.Scope>;
-  readonly drain: Effect.Effect<void>;
-}
-
-export class ProviderRateLimitsReactor extends Context.Service<
-  ProviderRateLimitsReactor,
-  ProviderRateLimitsReactorShape
->()("t3/orchestration/Services/ProviderRateLimitsReactor") {}
+export class ProviderRateLimitsReactor extends Context.Service<ProviderRateLimitsReactor>()(
+  "t3/orchestration/ProviderRateLimitsReactor",
+  {
+    /**
+     * Start forwarding `account.rate-limits.updated` observations into the
+     * provider registry. Must be run in a scope so the worker is finalized on
+     * shutdown.
+     */
+    readonly start: () => Effect.Effect<void, never, Scope.Scope>,
+    /** Resolves once every observed event has been applied. Test seam. */
+    readonly drain: Effect.Effect<void>,
+  },
+) {}

Posted via Macroscope — Effect Service Conventions

export class KimiCodeUsageFetchError extends Schema.TaggedErrorClass<KimiCodeUsageFetchError>()(
"KimiCodeUsageFetchError",
{
message: Schema.String,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

KimiCodeUsageFetchError keeps an unstructured message as its only real attribute, and the transport/decode paths below build that string from cause.message while discarding the underlying failure (Effect.mapError((cause) => new KimiCodeUsageFetchError({ message: ... }))). Service failures should carry stable structural attributes, derive message from them, and preserve the immediate error as cause so the chain and stack survive.

-    message: Schema.String,
     status: Schema.optionalKey(Schema.Number),
+    stage: Schema.Literals(["request", "unauthorized", "status", "decode"]),
+    cause: Schema.optional(Schema.Defect()),
   },
-) {}
+) {
+  override get message(): string {
+    // derived from `stage` (+ `status`), never from `cause`
+  }
+}

The four construction sites then pass stage/status plus cause instead of a pre-rendered message; the adapter can keep surfacing cause.message as ProviderAdapterRequestError.detail as it does today.

Posted via Macroscope — Effect Service Conventions

@macroscopeapp macroscopeapp Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

UI Consistency: 2 findings

Both are new code in this PR that rebuilds an existing shared primitive at the call site. Everything else reviewed here (the pinned rate-limit dock, the rate-limit popover's tooltipStyle + viewportClassName="p-0" composition, the new scope pages and crumbs, and the owner-local .composer-markdown-code rule for Lexical's generated DOM) follows the established contracts.

Posted via Macroscope — UI Consistency

Comment on lines +88 to +89
const MENU_LABEL_CLASS =
"px-2 pb-1 pt-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/70";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

MENU_LABEL_CLASS rebuilds MenuGroupLabel as a plain <div> (lines 218, 233, 249, 290, 331, 352). That drops Base UI's Menu.GroupLabel semantics — the enclosing MenuGroup no longer gets an aria-labelledby pointing at the label, so screen readers announce these radio groups unlabelled — and it diverges from every other menu in the app (BranchToolbar, ProjectScriptsControl, PullRequestListFilters, ProjectSettingsPanel, and ThreadWorkspace in this same PR all use MenuGroupLabel).

Consider <MenuGroupLabel>Group by</MenuGroupLabel> at each site. If the small-caps treatment is deliberate, keep it by passing it through the primitive (<MenuGroupLabel className={MENU_LABEL_CLASS}>) so the label semantics survive.

Posted via Macroscope — UI Consistency

Comment on lines +324 to +337
<button
type="button"
aria-label={`Delete workspace ${entry.name}`}
className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground group-hover/saved:opacity-100 focus-visible:opacity-100"
onClick={(event) => {
// The row itself restores; deleting must not also load the
// workspace it just removed.
event.stopPropagation();
event.preventDefault();
deleteWorkspace(entry.id);
}}
>
<Trash2Icon className="size-3" />
</button>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This raw <button> reconstructs Button size="icon-micro" variant="ghost-muted" (same size-5 rounded-sm geometry, same muted-ghost hover), but loses the primitive's focus-visible:ring-2 ring-ring and its pointer-coarse:after:min-h-11/min-w-11 touch target — so on a touch device this stays a 20px hit area. SidebarPinnedRateLimitsDock in this same PR uses the primitive for exactly this affordance.

Button is already imported here:

Suggested change
<button
type="button"
aria-label={`Delete workspace ${entry.name}`}
className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground group-hover/saved:opacity-100 focus-visible:opacity-100"
onClick={(event) => {
// The row itself restores; deleting must not also load the
// workspace it just removed.
event.stopPropagation();
event.preventDefault();
deleteWorkspace(entry.id);
}}
>
<Trash2Icon className="size-3" />
</button>
<Button
aria-label={`Delete workspace ${entry.name}`}
className="shrink-0 opacity-0 group-hover/saved:opacity-100 focus-visible:opacity-100"
onClick={(event) => {
// The row itself restores; deleting must not also load the
// workspace it just removed.
event.stopPropagation();
event.preventDefault();
deleteWorkspace(entry.id);
}}
size="icon-micro"
variant="ghost-muted"
>
<Trash2Icon className="size-3" />
</Button>

The tab close button at lines 454-464 is the same pattern; it at least matches the existing PanelTabCloseButton styling, so either reuse that primitive or give it the same Button treatment.

Posted via Macroscope — UI Consistency

tag: WS_METHODS.serverRefreshProviderRateLimits,
concurrency: {
mode: "singleFlight",
key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium state/server.ts:753

Concurrent refreshes for { environmentId: "a", instanceId: "b:c" } and { environmentId: "a:b", instanceId: "c" } share the key a:b:c, so the second caller receives the first request's promise and its provider rate limits are never refreshed. Use an injective key encoding instead of delimiter concatenation.

Suggested change
key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
🤖 Copy this AI Prompt to have your agent fix this:
In file @packages/client-runtime/src/state/server.ts around line 753:

Concurrent refreshes for `{ environmentId: "a", instanceId: "b:c" }` and `{ environmentId: "a:b", instanceId: "c" }` share the key `a:b:c`, so the second caller receives the first request's promise and its provider rate limits are never refreshed. Use an injective key encoding instead of delimiter concatenation.

visit(child);
continue;
}
text += INLINE_TOKEN_PLACEHOLDER.repeat(child.getTextContentSize());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium components/composerMarkdownHighlight.ts:158

Inline chips do not form a syntax boundary, so delimiters on opposite sides of a chip are highlighted as one markdown construct—for example, * before and after a chip is scanned as ** and both real delimiters are formatted. Use whitespace-only filler for chips so emphasis and links cannot span across an opaque inline token.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/composerMarkdownHighlight.ts around line 158:

Inline chips do not form a syntax boundary, so delimiters on opposite sides of a chip are highlighted as one markdown construct—for example, `*` before and after a chip is scanned as `**` and both real delimiters are formatted. Use whitespace-only filler for chips so emphasis and links cannot span across an opaque inline token.

const active: TThread[] = [];
const snoozed: TThread[] = [];
const settled: TThread[] = [];
for (const thread of input.threads) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium src/workspaceScope.ts:69

Archived threads reappear in scope shelves and continue inflating project counts after archiving. shelveScopeThreads processes every supplied shell, and summarizeEnvironmentProjects includes every shell in totals, active counts, and recency; both callers pass raw useThreadShells() results, unlike the sidebar's archivedAt === null filter. Filter archived threads before shelving and summarizing so archive removes them from these views too.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/workspaceScope.ts around line 69:

Archived threads reappear in scope shelves and continue inflating project counts after archiving. `shelveScopeThreads` processes every supplied shell, and `summarizeEnvironmentProjects` includes every shell in totals, active counts, and recency; both callers pass raw `useThreadShells()` results, unlike the sidebar's `archivedAt === null` filter. Filter archived threads before shelving and summarizing so archive removes them from these views too.

function spansFor(text: string): readonly ComposerMarkdownSpan[] {
if (cachedText !== text) {
cachedText = text;
cachedSpans = scanComposerMarkdown(text);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium components/composerMarkdownHighlight.ts:293

A CRLF fenced block remains open after spansFor calls scanComposerMarkdown, so all following prompt text is painted as code. The scanner does not recognize the \r in "```\r\n" before the closing fence; make the scan CRLF-aware while preserving offsets used to apply spans.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/composerMarkdownHighlight.ts around line 293:

A CRLF fenced block remains open after `spansFor` calls `scanComposerMarkdown`, so all following prompt text is painted as code. The scanner does not recognize the `\r` in `"[code fence]\r\n"` before the closing fence; make the scan CRLF-aware while preserving offsets used to apply spans.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium

const orderedThreads = useMemo(

orderedThreads includes every activeThreads entry, so threads inside collapsed sections still consume jump indices and traversal positions; shortcuts can navigate to hidden rows and visible rows receive the wrong labels. Build the active portion from the visible activeThreadRows instead, and include it in the memo dependencies.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/Sidebar.tsx around line 2816:

`orderedThreads` includes every `activeThreads` entry, so threads inside collapsed sections still consume jump indices and traversal positions; shortcuts can navigate to hidden rows and visible rows receive the wrong labels. Build the active portion from the visible `activeThreadRows` instead, and include it in the memo dependencies.

detail: "An active Codex session is required to refresh plan limits.",
});
}
const response = yield* session.runtime.readRateLimits.pipe(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 High Layers/CodexAdapter.ts:2011

refreshRateLimits can remain pending indefinitely when Codex keeps the app-server process alive but never answers account/rateLimits/read, so the manual plan-limit refresh and its WebSocket RPC never complete. Add a bounded timeout around session.runtime.readRateLimits and map the timeout to a ProviderAdapterRequestError so the request returns an error instead of hanging.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/provider/Layers/CodexAdapter.ts around line 2011:

`refreshRateLimits` can remain pending indefinitely when Codex keeps the app-server process alive but never answers `account/rateLimits/read`, so the manual plan-limit refresh and its WebSocket RPC never complete. Add a bounded timeout around `session.runtime.readRateLimits` and map the timeout to a `ProviderAdapterRequestError` so the request returns an error instead of hanging.

...window,
...(hasMultipleBuckets
? {
id: `${bucketId}:${window.id}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium provider/providerRateLimits.ts:503

After a multi-bucket full read, a sparse update for a bucket appends a second bare primary/secondary window instead of updating that bucket's ${bucketId}:${window.id} entry, so the original window remains stale and the UI shows duplicate limits. normalizeCodexRateLimits does not incorporate the payload's limitId; make the full-read and sparse-event paths use the same bucket-qualified IDs.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/provider/providerRateLimits.ts around line 503:

After a multi-bucket full read, a sparse update for a bucket appends a second bare `primary`/`secondary` window instead of updating that bucket's `${bucketId}:${window.id}` entry, so the original window remains stale and the UI shows duplicate limits. `normalizeCodexRateLimits` does not incorporate the payload's `limitId`; make the full-read and sparse-event paths use the same bucket-qualified IDs.

readonly target: Extract<ThreadWorkspaceTarget, { routeKind: "draft" }>;
}) {
return (
<ChatViewWithoutDiffWorkerPool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium thread-workspace/ThreadWorkspace.tsx:643

Opening a draft on a mobile viewport renders the composer collapsed instead of the required expanded draft entry UI. DraftThreadPane omits forceExpandedMobileComposer, so ChatViewWithoutDiffWorkerPool defaults it to false and never enables mobile expansion for the draft hero composer.

-    <ChatViewWithoutDiffWorkerPool
+    <ChatViewWithoutDiffWorkerPool
+      forceExpandedMobileComposer={true}
🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/thread-workspace/ThreadWorkspace.tsx around line 643:

Opening a draft on a mobile viewport renders the composer collapsed instead of the required expanded draft entry UI. `DraftThreadPane` omits `forceExpandedMobileComposer`, so `ChatViewWithoutDiffWorkerPool` defaults it to `false` and never enables mobile expansion for the draft hero composer.

);
const handleThreadSortOrderChange = useCallback(
(sortOrder: SidebarThreadSortOrder) => {
updateClientSettings({ sidebarThreadSortOrder: sortOrder });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium components/Sidebar.tsx:2571

Selecting Date created or Last activity only updates the menu readout; the inbox order never changes because activeThreads is always passed to sortThreadsForSidebar(active) without sidebarThreadSortOrder. Pass the selected sort order through to the sorting logic so the chosen option affects the rendered rows.

🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/Sidebar.tsx around line 2571:

Selecting `Date created` or `Last activity` only updates the menu readout; the inbox order never changes because `activeThreads` is always passed to `sortThreadsForSidebar(active)` without `sidebarThreadSortOrder`. Pass the selected sort order through to the sorting logic so the chosen option affects the rendered rows.

Comment on lines +311 to +313
const target = selectActiveThreadWorkspaceTarget(
useThreadWorkspaceStore.getState(),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium thread-workspace/ThreadWorkspace.tsx:311

Restoring a workspace with an empty active pane leaves the old URL in place, so the subsequent route binding inserts the previously open thread into the restored workspace. selectActiveThreadWorkspaceTarget returns null for that pane and skips navigation; fall back to another restored tab when the active pane has none.

-                    const target = selectActiveThreadWorkspaceTarget(
-                      useThreadWorkspaceStore.getState(),
-                    );
+                    const restoredState = useThreadWorkspaceStore.getState();
+                    const target =
+                      selectActiveThreadWorkspaceTarget(restoredState) ??
+                      restoredState.panes.flatMap((pane) => pane.tabs)[0] ??
+                      null;
🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/web/src/components/thread-workspace/ThreadWorkspace.tsx around lines 311-313:

Restoring a workspace with an empty active pane leaves the old URL in place, so the subsequent route binding inserts the previously open thread into the restored workspace. `selectActiveThreadWorkspaceTarget` returns `null` for that pane and skips navigation; fall back to another restored tab when the active pane has none.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

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 using high effort and found 3 potential issues.

Fix All in Cursor

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

Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit e0968af. Configure here.

return token === undefined
? null
: { usagesUrl: `${override.replace(/\/+$/, "")}/usages`, token };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Kimi override hijacks official Claude

Medium Severity

resolveKimiCodeUsageSource treats a set KIMI_CODE_BASE_URL plus any Anthropic token as enough to classify the instance as Kimi, and it never checks ANTHROPIC_BASE_URL. Instance env is merged on top of process.env, so a shell-level Kimi CLI override makes every Claude instance — including official Anthropic — skip get_usage, fetch Kimi /usages after each turn, and show the wrong account's limits.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e0968af. Configure here.

label: bucketLabel ? `${window.label} (${bucketLabel})` : window.label,
}
: {}),
}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex refresh IDs break live merge

Medium Severity

A full Codex refresh prefixes window ids (codex:primary) when multiple named buckets exist, but live account/rateLimits/updated snapshots keep unprefixed ids (primary) and the reactor merges by default. After Refresh, the next turn adds duplicate bars and leaves the prefixed windows stale.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e0968af. Configure here.

seven_day_opus: { label: "Weekly (Opus)", kind: "weekly" },
seven_day_sonnet: { label: "Weekly (Sonnet)", kind: "weekly" },
seven_day_oauth_apps: { label: "Weekly (apps)", kind: "weekly" },
overage: { label: "Extra usage", kind: "credits" },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude extra-usage window IDs diverge

Low Severity

Live Claude rate_limit_events map overage to window id overage, while the authoritative get_usage snapshot uses extra_usage for the same Extra usage bar. A later sparse event therefore merges a second credits window instead of updating the existing one.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e0968af. Configure here.

@macroscopeapp

macroscopeapp Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Approvability

Verdict: Not approved

Macroscope's review found this PR not approvable — This is a large production-surface change that combines provider-limit networking and persistence with a sidebar overhaul, multi-pane workspace, new routes, and cross-platform UI behavior. Unresolved findings include wrong-account Kimi requests and inconsistent Codex limit state, alongside other medium/high-risk lifecycle and state issues, so human review is needed.

Not approved because:

  • 15 blocking correctness issues found at or above your repo's Minimum Blocking Severity

Adjust the Minimum Blocking Severity for this repo — including turning it Off — in Settings. You can add or adjust custom eligibility rules. Learn more.

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

Labels

size:XXL 1,000+ changed lines (additions + deletions). vouch:unvouched Author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant