Skip to content

Commit 3d051d6

Browse files
authored
fix(app): reset the session route when switching tabs after a session error (#61585)
1 parent 0c44147 commit 3d051d6

7 files changed

Lines changed: 653 additions & 268 deletions

File tree

‎packages/app/src/runtime/server/errors.ts‎

Lines changed: 35 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { Predicate } from "effect"
2+
13
export type ConfigInvalidError = {
24
name: "ConfigInvalidError"
35
data: {
@@ -27,73 +29,67 @@ function tr(translator: Translator | undefined, key: string, text: string, vars?
2729
return out
2830
}
2931

30-
export function formatServerError(error: unknown, translate?: Translator, fallback?: string) {
31-
const unwrapped = unwrapNamedError(error)
32+
export function formatServerError(cause: unknown, translate?: Translator, fallback?: string) {
33+
const unwrapped = unwrapNamedError(cause)
3234

3335
if (isConfigInvalidErrorLike(unwrapped)) return parseReadableConfigInvalidError(unwrapped, translate)
3436

3537
if (isProviderModelNotFoundErrorLike(unwrapped)) return parseReadableProviderModelNotFoundError(unwrapped, translate)
3638

3739
if (
38-
typeof unwrapped === "object" &&
39-
unwrapped !== null &&
40-
"message" in unwrapped &&
41-
typeof unwrapped.message === "string" &&
40+
Predicate.isObjectOrArray(unwrapped) &&
41+
Predicate.hasProperty(unwrapped, "message") &&
42+
Predicate.isString(unwrapped.message) &&
4243
unwrapped.message
4344
)
4445
return unwrapped.message
4546

46-
if (error instanceof Error && error.message) return error.message
47+
if (cause instanceof Error && cause.message) return cause.message
4748

48-
if (typeof error === "string" && error) return error
49+
if (Predicate.isString(cause) && cause) return cause
4950

5051
if (fallback) return fallback
5152

5253
return tr(translate, "error.chain.unknown", "Unknown error")
5354
}
5455

55-
function unwrapNamedError(error: unknown): unknown {
56-
if (!(error instanceof Error) || !error.cause || typeof error.cause !== "object") return error
57-
58-
if ("body" in error.cause) return (error.cause as Record<string, unknown>).body
59-
60-
return error.cause
61-
}
62-
63-
// Client-synthesized session not-found errors share one constructor and
64-
// predicate so the message contract cannot drift between route session
65-
// resolution (session-resolution.ts) and not-found fallback matching (session.tsx).
66-
const sessionNotFoundMessage = (sessionID: string) => `Session not found: ${sessionID}`
56+
function unwrapNamedError(cause: unknown) {
57+
if (!(cause instanceof Error) || !Predicate.isObjectOrArray(cause.cause)) return cause
6758

68-
export function sessionNotFoundError(sessionID: string) {
69-
return new Error(sessionNotFoundMessage(sessionID))
70-
}
59+
if (Predicate.hasProperty(cause.cause, "body")) return cause.cause.body
7160

72-
export function isLocalSessionNotFoundError(error: unknown, sessionID: string) {
73-
return error instanceof Error && error.message === sessionNotFoundMessage(sessionID)
61+
return cause.cause
7462
}
7563

76-
export function isSessionNotFoundError(error: unknown, sessionID: string) {
77-
const unwrapped = unwrapNamedError(error)
64+
export function isSessionNotFoundError(cause: unknown, sessionID: string) {
65+
const unwrapped = unwrapNamedError(cause)
7866

79-
if (typeof unwrapped !== "object" || unwrapped === null) return false
80-
const value = unwrapped as Record<string, unknown>
81-
82-
return value._tag === "SessionNotFoundError" && value.sessionID === sessionID
67+
return (
68+
Predicate.isObjectOrArray(unwrapped) &&
69+
Predicate.isTagged(unwrapped, "SessionNotFoundError") &&
70+
Predicate.hasProperty(unwrapped, "sessionID") &&
71+
unwrapped.sessionID === sessionID
72+
)
8373
}
8474

8575
function isConfigInvalidErrorLike(error: unknown): error is ConfigInvalidError {
86-
if (typeof error !== "object" || error === null) return false
87-
const o = error as Record<string, unknown>
88-
89-
return o.name === "ConfigInvalidError" && typeof o.data === "object" && o.data !== null
76+
return (
77+
Predicate.isObjectOrArray(error) &&
78+
Predicate.hasProperty(error, "name") &&
79+
error.name === "ConfigInvalidError" &&
80+
Predicate.hasProperty(error, "data") &&
81+
Predicate.isObjectOrArray(error.data)
82+
)
9083
}
9184

9285
function isProviderModelNotFoundErrorLike(error: unknown): error is ProviderModelNotFoundError {
93-
if (typeof error !== "object" || error === null) return false
94-
const o = error as Record<string, unknown>
95-
96-
return o.name === "ProviderModelNotFoundError" && typeof o.data === "object" && o.data !== null
86+
return (
87+
Predicate.isObjectOrArray(error) &&
88+
Predicate.hasProperty(error, "name") &&
89+
error.name === "ProviderModelNotFoundError" &&
90+
Predicate.hasProperty(error, "data") &&
91+
Predicate.isObjectOrArray(error.data)
92+
)
9793
}
9894

9995
export function parseReadableConfigInvalidError(errorInput: ConfigInvalidError, translator?: Translator) {
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import { expect, test } from "bun:test"
2+
import type { ServerHealth } from "@/runtime/server/health"
3+
import {
4+
createSessionResolutionState,
5+
sessionRouteView,
6+
transitionSessionResolution,
7+
type SessionResolutionEffect,
8+
type SessionResolutionEvent,
9+
type SessionResolutionState,
10+
type SessionResolutionTransition,
11+
type SessionRouteView,
12+
} from "./resolution-machine"
13+
14+
type Session = { id: string }
15+
16+
type Event = SessionResolutionEvent<Session, string>
17+
18+
type State = SessionResolutionState<Session, string>
19+
20+
const target = (sessionID: string, scope = "server-a") => ({ scope, sessionID })
21+
22+
function open(
23+
sessionID: string,
24+
input: { cached?: Session; connected?: boolean; refresh?: boolean; scope?: string } = {},
25+
): Event {
26+
return {
27+
type: "target.changed",
28+
target: target(sessionID, input.scope),
29+
cached: input.cached,
30+
connected: input.connected ?? true,
31+
refresh: input.refresh ?? true,
32+
}
33+
}
34+
35+
function replay(events: Event[]) {
36+
const initial: SessionResolutionTransition<Session, string> = { state: createSessionResolutionState(), effects: [] }
37+
38+
return events.reduce((current, event) => transitionSessionResolution(current.state, event), initial)
39+
}
40+
41+
// The SDK rejects with the decoded response body.
42+
const notFound = (sessionID: string) =>
43+
JSON.parse(`{"_tag":"SessionNotFoundError","sessionID":"${sessionID}","message":"Session not found"}`)
44+
45+
// The route used to rethrow these outcomes into an error boundary that every session tab on the
46+
// server shares, so the next tab kept showing the previous session's error.
47+
test.each([
48+
{ name: "missing", error: notFound("ses_a"), shown: "not-found" },
49+
{ name: "failed", error: new Error("boom"), shown: "error" },
50+
])("a $name session does not outlive a switch to another tab", ({ error, shown }) => {
51+
const failed = replay([open("ses_a"), { type: "sync.failed", target: target("ses_a"), attempt: 1, error }])
52+
expect(sessionRouteView(failed.state, undefined)).toMatchObject({ type: shown, sessionID: "ses_a" })
53+
54+
const next = transitionSessionResolution(failed.state, open("ses_b"))
55+
expect(sessionRouteView(next.state, undefined)).toEqual({ type: "resolving", sessionID: "ses_b" })
56+
expect(next.effects).toEqual([
57+
{ type: "sync.transcript", target: target("ses_b") },
58+
{ type: "sync.metadata", target: target("ses_b"), attempt: 2 },
59+
])
60+
61+
const cached = transitionSessionResolution(failed.state, open("ses_b", { cached: { id: "ses_b" } }))
62+
expect(sessionRouteView(cached.state, undefined)).toEqual({
63+
type: "ready",
64+
sessionID: "ses_b",
65+
session: { id: "ses_b" },
66+
})
67+
})
68+
69+
test("ignores results from an earlier visit to the same session", () => {
70+
const returned = replay([open("ses_a"), open("ses_b"), open("ses_a")])
71+
expect(returned.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 3 })
72+
73+
const late: Event[] = [
74+
{ type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("boom") },
75+
{ type: "sync.settled", target: target("ses_a"), attempt: 1, session: undefined },
76+
{ type: "sync.settled", target: target("ses_b"), attempt: 2, session: { id: "ses_b" } },
77+
]
78+
79+
late.forEach((event) => expect(transitionSessionResolution(returned.state, event).state).toBe(returned.state))
80+
81+
const current: Event = { type: "sync.settled", target: target("ses_a"), attempt: 3, session: undefined }
82+
expect(transitionSessionResolution(returned.state, current).state).toEqual({
83+
status: "not-found",
84+
target: target("ses_a"),
85+
attempt: 3,
86+
})
87+
})
88+
89+
test("a replaced session store is a new target", () => {
90+
const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
91+
const replaced = transitionSessionResolution(ready.state, open("ses_a", { scope: "server-b" }))
92+
expect(replaced.state).toEqual({ status: "resolving", target: target("ses_a", "server-b"), attempt: 2 })
93+
94+
const stale: Event = { type: "cache.changed", target: target("ses_a"), session: undefined }
95+
expect(transitionSessionResolution(replaced.state, stale).state).toBe(replaced.state)
96+
})
97+
98+
test.each<{ name: string; event: Event; effects: SessionResolutionEffect<string>["type"][] }>([
99+
{
100+
name: "a cached session without refresh loads only its transcript",
101+
event: open("ses_a", { cached: { id: "ses_a" }, refresh: false }),
102+
effects: ["sync.transcript"],
103+
},
104+
{
105+
name: "a cached session with refresh also reloads its metadata",
106+
event: open("ses_a", { cached: { id: "ses_a" } }),
107+
effects: ["sync.transcript", "sync.metadata"],
108+
},
109+
{ name: "a disconnected route waits to load", event: open("ses_a", { connected: false }), effects: [] },
110+
])("$name", ({ event, effects }) => {
111+
expect(replay([event]).effects.map((effect) => effect.type)).toEqual(effects)
112+
})
113+
114+
test("reconnecting retries a failed session and refreshes a resolved one in place", () => {
115+
const connected: Event = { type: "connected", target: target("ses_a"), refresh: true }
116+
const failed = replay([open("ses_a"), { type: "sync.failed", target: target("ses_a"), attempt: 1, error: "offline" }])
117+
const retried = transitionSessionResolution(failed.state, connected)
118+
expect(retried.state).toEqual({ status: "resolving", target: target("ses_a"), attempt: 2 })
119+
expect(retried.effects.map((effect) => effect.type)).toEqual(["sync.transcript", "sync.metadata"])
120+
121+
const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
122+
const refreshed = transitionSessionResolution(ready.state, connected)
123+
expect(refreshed.state).toBe(ready.state)
124+
expect(refreshed.effects.map((effect) => effect.type)).toEqual(["sync.transcript", "sync.metadata"])
125+
})
126+
127+
test("a resolved session stays visible through a failed refresh until it leaves the cache", () => {
128+
const ready = replay([open("ses_a", { cached: { id: "ses_a" } })])
129+
const failure: Event = { type: "sync.failed", target: target("ses_a"), attempt: 1, error: new Error("boom") }
130+
expect(transitionSessionResolution(ready.state, failure).state).toBe(ready.state)
131+
132+
const deleted: Event = { type: "cache.changed", target: target("ses_a"), session: undefined }
133+
expect(transitionSessionResolution(ready.state, deleted).state).toEqual({
134+
status: "not-found",
135+
target: target("ses_a"),
136+
attempt: 1,
137+
})
138+
})
139+
140+
test("unmounting ignores later results", () => {
141+
const disposed = replay([open("ses_a"), { type: "disposed" }])
142+
expect(disposed.state).toEqual({ status: "idle", attempt: 2 })
143+
144+
const late: Event = { type: "sync.settled", target: target("ses_a"), attempt: 1, session: { id: "ses_a" } }
145+
expect(transitionSessionResolution(disposed.state, late).state).toBe(disposed.state)
146+
})
147+
148+
const resolving: State = { status: "resolving", target: target("ses_a"), attempt: 1 }
149+
150+
const resolved: State = { status: "ready", target: target("ses_a"), session: { id: "ses_a" }, attempt: 1 }
151+
152+
const missing: State = { status: "not-found", target: target("ses_a"), attempt: 1 }
153+
154+
test.each<{ name: string; health: ServerHealth; state: State; view: SessionRouteView<Session>["type"] }>([
155+
{
156+
name: "incompatible wins over a resolved session",
157+
health: { healthy: true, incompatible: true },
158+
state: resolved,
159+
view: "incompatible",
160+
},
161+
{
162+
name: "an unreachable server explains a pending session",
163+
health: { healthy: false },
164+
state: resolving,
165+
view: "unreachable",
166+
},
167+
{
168+
name: "a running health check keeps waiting",
169+
health: { healthy: false, checking: true },
170+
state: resolving,
171+
view: "resolving",
172+
},
173+
{
174+
name: "a rejected credential keeps waiting",
175+
health: { healthy: false, unauthorized: true },
176+
state: resolving,
177+
view: "resolving",
178+
},
179+
{
180+
name: "an unreachable server keeps a known outcome",
181+
health: { healthy: false },
182+
state: missing,
183+
view: "not-found",
184+
},
185+
])("view: $name", ({ health, state, view }) => {
186+
expect(sessionRouteView(state, health).type).toBe(view)
187+
})

0 commit comments

Comments
 (0)