Files
paperclip/scripts/check-query-error-rendering.mjs
a3313f6944 fix(ui): complete read recovery and enforce query error rendering (#18822)
## Thinking Path

> - Paperclip lets people manage agent work through the board.
> - The board reads task, agent, settings, plugin, and run data from the
server.
> - A deploy can interrupt those reads after content is already visible.
> - Local error branches can replace that content with an error or show
raw codes.
> - This pull request moves the remaining reads to the shared recovery
behavior.
> - The query-error guard prevents new local error patterns from
returning.

## Linked Issues or Issue Description

**What happened?**
Loaded lists, settings, task panels, and manual reads could clear their
content or show errors during a server restart. Some reads also disabled
the shared retry policy.

**Expected behavior**
Keep loaded content during a temporary failure. Show the shared
connection banner. Retry reads after recovery. Replace content after a
real access denial or missing resource, with readable copy.

**Steps to reproduce**
Open a task, settings page, or run log. Return 503 with
`tenant_app_unavailable` from the API. Restore the API and check that
content refreshes. Repeat with 403 and 404 to check the failure state.

Related merged work: Refs #15754, Refs #15772, Refs #17960. This change
covers remaining reads and enforcement. Browser persistence and the
outage browser suite follow separately.

## What Changed

- Repair an existing PostgreSQL deadline fixture at UTC boundaries. A
daily cap defers a heartbeat until both its original interval and the
next UTC day allow it. Keep the counted run in its seeded day and cover
noon, just before midnight and the first second after midnight with
explicit clocks and real PostgreSQL. Production scheduling is unchanged.

- Integrate the saved list, settings, shell, task, and manual-read
recovery changes against current master. Preserve the current task,
Inbox, and run-log structure.
- Add `useResilientFetch` for component-local reads. Preserve loaded
data, cancel stale requests, and retry through the shared connectivity
policy. Keep browser and pairing capabilities in memory.
- Retain run log chunks across stream changes and catch up after
recovery without duplicate chunks or stalled requests.
- Keep genuine authorization and missing-resource failures visible.
Translate known single-word codes such as `forbidden`. Show known skills
and disconnected-app failures before sibling loading states. Keep Retry
bound to its failed request.
- Make the query-error guard enforce by default and run it in the CI
policy job. Document the narrow exceptions and the read recovery
contract.
- Invalidate pending OAuth discovery when the operator leaves setup or
its context changes. Keep reserved-popup cleanup bound to the current
attempt.

## Verification

- Current read head `09d1db29dea` is merge-ready: all 59 check runs are
completed (54 successful, three skipped, two neutral), the legacy Snyk
status is successful, and both required `ci / verify` and `ci / e2e`
gates pass. Greptile Apex reviewed this exact head at 5/5 with no
unresolved threads; the branch has no merge conflicts. The current CI
run is `41748339602`.
- Current read head `09d1db29dea` includes master `683fa4725e9`. The
latest change touches only the existing server deadline test fixture.
Application source remains the previously verified `86376fa751e`
revision: all 60 affected skills/disconnected-app tests and both
application UI typechecks passed, along with token gates and the
enforcing query-error guard. Those UI suites were not repeated for this
test-only repair.
- The fixture repair passes all seven deadline integration cases and the
complete server typecheck, including the server test layer. The old
assertion deterministically fails at 23:59:06.888 UTC; its
one-second-old run also fails the first-second-of-day probe. The
corrected fixture passes noon and both midnight probes. The permanent
three-case coverage uses seeded 2099 clocks.
- Twelve new regressions fail against the previous implementation. Both
skills variants and disconnected-app pages show either request's 403 or
429 while the sibling pauses or remains fetching. Permission failures
stay visible. Retry stays usable for its failed request and recovers
independently. An initial test-fixture query-key typo was corrected
before the passing run. The finding is replied to and resolved. Greptile
reviewed prior application revision `86376fa751e` at 5/5 with no new
actionable findings or unresolved threads. The current test-only head
has now received its own Apex 5/5 review with no unresolved threads, and
its CI is successful as recorded above.
- The preceding OAuth fix passed all 237 setup tests on both application
branches. Its ten regressions prove that Back, Cancel, unmount, or
context changes retire initial discovery without creating a connection,
caching old identities, navigating an abandoned popup, or closing a
newer attempt.
- Earlier master integration `e992f770339` passed all 309 tests across
eight affected Slack, recovery, retry, submission and task files, plus
UI typecheck, token gates, enforcing query-error scan and seven guard
tests. The integration preserves Slack workspace reconnect and shared
recovery, readable execution errors, source-inspection company scoping,
and current submission behavior. Newly inherited retained-file recovery
controls keep cached data through transient failures and hide it after
definitive denial.
- The preceding cache head `97c0bc3966f` passed 1,038 focused
cache/write/editor/account/task/API tests. All 22 built-UI
outage/write/loading cases passed in 4.7 minutes on exact browser head
`b7deaaee5da`, with strict checking of all three specs. The latest
skills/app rendering fix is covered by its affected component suites;
those broader cases were not repeated for this separate read path.
- Historical broader UI, CLI and build results and unresolved aggregate
server/DB/adapter failures remain in the PR discussion. Interrupted CI
runs were audited and recorded separately; they are not counted as
passes. Controlled local outages do not prove hosted authentication or a
real Cloud restart/deploy. Real hosted acceptance remains required after
merge and deployment.

Commands for the latest fix:

```sh
pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
node scripts/check-query-error-rendering.mjs --enforce --summary
```

## Risks

This migration touches many read surfaces. The main risks are initial
loading, request cancellation, retained authorization state, and run-log
paging. The tests cover those states. There are no server, schema,
dependency, or API contract changes. The follow-up browser suite and
hosted deploy acceptance are required before release acceptance.

Recovered commits retain their original authors. If squash-merging,
preserve `Co-Authored-By: Bender (Fable) <[email protected]>`
and the Paperclip trailer.

## Model Used

OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool
use, and code execution. The context window size is not exposed. Saved
source commits keep their original authorship.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] The affected local tests pass; broader limitations are recorded
above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <[email protected]>
Co-authored-by: Paperclip <[email protected]>
Co-authored-by: Bender (Fable) <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-04 14:07:18 -08:00

215 lines
8.6 KiB
JavaScript

#!/usr/bin/env node
/**
* Disconnect-handling guard: finds UI code that renders raw query
* errors or opts out of the shared retry policy.
*
* During an outage the app shows one connection banner and keeps loaded data
* on screen. These patterns break that:
*
* raw-error-message {error.message}, {query.error?.message}
* cast-error-message {(error as Error).message}
* is-error-render isError ? … / isError && … (usually hides cached data)
* retry-false retry: false (skips transient retry; use the defaults
* in ui/src/lib/query-client.ts)
*
* Use `describeError` (ui/src/api/errors.ts) for copy and render cached data
* before errors. Intentional exceptions go in ALLOWLIST below as
* "<path>:<rule>" with a reason.
*
* Enforcing by default: prints findings and exits 0, except for findings in
* ENFORCED_FILES (surfaces already migrated), which always exit 1. `--enforce`
* exits 1 on any finding outside the allowlist (CI turns this on once the
* long tail migrates).
*
* Usage: node scripts/check-query-error-rendering.mjs [--enforce] [--summary]
*/
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const defaultScanRoot = join(repoRoot, "ui/src");
export const RULES = [
{
id: "raw-error-message",
description: "renders a raw error message; use describeError()",
pattern: /\{\s*[\w$.?!]*\b(?:error|err|e|[a-z]\w*Error)\s*[?!]?\.message\s*\}/,
},
{
id: "cast-error-message",
description: "renders a cast error message; use describeError()",
pattern: /\{\s*\(\s*[\w$.?!]+\s+as\s+(?:Error|ApiError)\s*\)\s*\??\.message\s*\}/,
},
{
id: "is-error-render",
description: "branches rendering on isError; render cached data first",
// `isError ?` / `isError &&`, not `isError?.x`, `isError ?? x`, or `isError?: boolean`.
pattern: /\bisError\s*(?:\?(?![.?:])|&&)/,
},
{
id: "retry-false",
description: "disables retry; rely on the query-client defaults",
pattern: /\bretry\s*:\s*false\b/,
},
];
/**
* Intentional exceptions, as "<repo-relative path>:<rule id>". Each entry needs
* a reason. The list shrinks as surfaces migrate to the shared error handling.
*/
export const ALLOWLIST = new Set([
"ui/src/artifact-directions/main.tsx:retry-false",
"ui/src/wizard-preview-main.tsx:retry-false",
"ui/src/fixtures/TaskChatPerfHarness.tsx:retry-false",
"ui/src/pages/NewAgent.test-support.tsx:retry-false",
"ui/src/components/TaskChatThread.tsx:is-error-render",
"ui/src/components/transcript/RunTranscriptView.tsx:is-error-render",
"ui/src/components/task-chat/transcript-adapter.ts:is-error-render",
"ui/src/lib/issue-chat-messages.ts:is-error-render",
"ui/src/lib/account-scope.ts:retry-false",
"ui/src/lib/copilot-task-model-catalog.ts:retry-false",
]);
/**
* Files already moved onto the shared read handling (`useQueryView` /
* `<QueryView>` in ui/src/components/QueryView.tsx). A finding in one of these
* fails the check even in report-only mode, so a migrated surface cannot
* quietly regress. Add a file here when you migrate it; mark an intentional
* exception on its line with `// query-error-ok: <reason>`.
*/
export const ENFORCED_FILES = new Set([
"ui/src/components/AgentChatPicker.tsx",
"ui/src/components/AgentConversationSidebar.tsx",
"ui/src/components/AgentConversationsSidebar.tsx",
"ui/src/components/BreadcrumbBar.production.tsx",
"ui/src/components/BreadcrumbBar.tsx",
"ui/src/components/CaseRevisionRail.tsx",
"ui/src/components/chat/AgentWorkPanels.tsx",
"ui/src/components/FileViewerSheet.tsx",
"ui/src/components/IssueRelatedWorkPanel.tsx",
"ui/src/components/IssueShareSheet.tsx",
"ui/src/components/issue-properties/external-object-rows.tsx",
"ui/src/components/NewIssueDialog.tsx",
"ui/src/components/QueryView.tsx",
"ui/src/components/Sidebar.production.tsx",
"ui/src/components/Sidebar.tsx",
"ui/src/components/SidebarAgentChats.tsx",
"ui/src/components/task-side-panel/TaskAttachmentPanel.tsx",
"ui/src/components/task-side-panel/TaskDocumentPanel.tsx",
"ui/src/components/task-side-panel/TaskSkillPanel.tsx",
"ui/src/components/UnprefixedExecutionWorkspaceRedirect.tsx",
"ui/src/components/WorkspaceFileBrowser.tsx",
"ui/src/hooks/useIssueExternalObjects.ts",
"ui/src/lib/query-client.ts",
"ui/src/pages/AgentChat.tsx",
"ui/src/pages/AgentChats.tsx",
"ui/src/pages/AgentDetail.production.tsx",
"ui/src/pages/AgentDetail.tsx",
"ui/src/pages/CaseDetail.tsx",
"ui/src/pages/CompanySettingsPluginPage.tsx",
"ui/src/pages/ExecutionWorkspaceDetail.tsx",
"ui/src/pages/GoalDetail.tsx",
"ui/src/pages/IssueDetail.tsx",
"ui/src/pages/PluginManager.tsx",
"ui/src/pages/ProjectDetail.tsx",
"ui/src/pages/ProjectWorkspaceDetail.tsx",
"ui/src/pages/SkillStudio.tsx",
"ui/src/pages/Workspaces.tsx",
"ui/src/plugins/bridge.ts",
"ui/src/plugins/launchers.tsx",
"ui/src/plugins/slots.tsx",
]);
function isCheckable(path) {
if (!/\.(ts|tsx)$/.test(path)) return false;
if (/\.(test|spec|stories)\.(ts|tsx)$/.test(path)) return false;
if (/\.d\.ts$/.test(path)) return false;
return true;
}
function walk(dir, out) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (entry.isDirectory()) walk(full, out);
else if (isCheckable(full)) out.push(full);
}
return out;
}
/** Findings for one file's source text. Lines ending in `// query-error-ok` are skipped. */
export function scanSource(sourceText, path) {
const findings = [];
const lines = sourceText.split("\n");
const checkable = lines.map((line) => {
const trimmed = line.trim();
return /\/\/\s*query-error-ok\b/.test(line)
|| trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*")
? " ".repeat(line.length) : line;
}).join("\n");
for (const rule of RULES) {
const pattern = new RegExp(rule.pattern.source, "g");
for (const match of checkable.matchAll(pattern)) {
const line = checkable.slice(0, match.index).split("\n").length;
findings.push({ path, line, rule: rule.id, text: lines[line - 1].trim() });
}
}
findings.sort((a, b) => a.line - b.line || RULES.findIndex((rule) => rule.id === a.rule) - RULES.findIndex((rule) => rule.id === b.rule));
return findings;
}
export function scanQueryErrorRendering({
root = defaultScanRoot,
allowlist = ALLOWLIST,
enforcedFiles = ENFORCED_FILES,
} = {}) {
const findings = [];
for (const file of walk(root, [])) {
const path = relative(repoRoot, file).split(sep).join("/");
for (const finding of scanSource(readFileSync(file, "utf8"), path)) {
if (allowlist.has(`${finding.path}:${finding.rule}`)) continue;
findings.push({ ...finding, enforced: enforcedFiles.has(finding.path) });
}
}
return findings;
}
function main() {
const args = new Set(process.argv.slice(2));
const enforce = !args.has("--report-only");
const summaryOnly = args.has("--summary");
const findings = scanQueryErrorRendering();
const enforcedFindings = findings.filter((finding) => finding.enforced);
if (!summaryOnly) {
for (const finding of findings) {
console.log(`${finding.path}:${finding.line} [${finding.rule}] ${finding.text}`);
}
}
const files = new Set(findings.map((finding) => finding.path));
console.log("");
console.log(`check-query-error-rendering: ${findings.length} finding(s) in ${files.size} file(s)`);
for (const rule of RULES) {
const count = findings.filter((finding) => finding.rule === rule.id).length;
console.log(` ${rule.id.padEnd(20)} ${String(count).padStart(5)} ${rule.description}`);
}
if (enforcedFindings.length > 0) {
// Always listed, even with --summary: these fail the check in every mode.
console.log("");
console.log(`${enforcedFindings.length} finding(s) in migrated files (ENFORCED_FILES); these always fail:`);
for (const finding of enforcedFindings) {
console.log(` ${finding.path}:${finding.line} [${finding.rule}] ${finding.text}`);
}
console.log("Render cached data first and use describeError(), or mark the line with `// query-error-ok: <reason>`.");
process.exitCode = 1;
}
if (!enforce) {
console.log("Explicit report-only mode: findings outside migrated files do not fail.");
return;
}
if (findings.length > 0) process.exitCode = 1;
}
if (resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) main();