Skip to content

Commit e9fffd3

Browse files
fix: Codex account switch releases the conversation, Reset usage on the limit banner (#82)
* fix(server): switching Codex accounts releases the conversation Detach only unloaded native threads still bound to the old session, but an account switch rebinds the thread to the new account's session in the same commit (and removes the old session's projection binding), so the root conversation was never unsubscribed and the old account's app-server held its writer lock indefinitely. The new account's resume then failed with 'This conversation is open in another Codex client'. Detach now also unloads this thread's same-driver native threads that were rebound away, taking the driver from the live runtime. Codex also keeps the lock ~60s after unsubscribe until its idle sweep closes the thread, so a resume refused for a thread this server released waits up to 90s for thread/closed and retries once; threads held by genuinely external clients still fail immediately. Model: muse-wonder-1.0-contributor (Muse Code) * feat(web,mobile): add Reset usage to the usage-limit banner The usage panel could spend a banked reset credit, but the usage-limit recovery banner/card only offered Resume at reset and Snooze until reset. When the limited account reports banked reset credits, the banner (web/desktop) and card (iOS/Android) now offer Reset usage, which confirms then redeems a credit via the existing consumeResetCredit command. Mobile's redemption hook moves to usage/useResetCredit.ts so the panel and card share it. Model: muse-wonder-1.0-contributor (Muse Code) * fix(server): expire completed Codex thread releases * fix(mobile): coalesce reset-credit confirmations Guard redemption before awaiting the RPC so confirmations already opened cannot submit overlapping reset requests. Release the guard on success, typed command failure or rejected transport, preserving execution-time permission checks and explicit user confirmation. Add focused hook regressions for duplicate approvals, each completion path, subsequent attempts and permission revocation. The exact hook source passed isolated controlled-promise checks with framework/transport stubs; the full React/vite-plus suite and changed-file gate remain hosted validation. * fix(web): guard overlapping reset-credit redemption Apply the mobile single-flight guard to the web/desktop usage hook while preserving its reset/message result for the recovery banner. Clear pending state after success, typed failure or transport rejection and recheck the current management permission on each attempt. Add a managed browser hook test for overlapping submissions, all completion paths and retry after permission changes. Hash-verified source extraction reproduced duplicate requests before and passed controlled-promise checks after; framework and RPC boundaries were stubbed. TypeScript syntax and whitespace checks passed. Actual React/browser execution, check:changed and full CI remain required; repository dependencies are unavailable locally. * fix(mobile): keep reset credit handling compatible with the React compiler * fix(web): keep reset credit handling compatible with React compiler * fix(codex): retain lock releases after cancelled resumes
1 parent 2368841 commit e9fffd3

16 files changed

Lines changed: 717 additions & 69 deletions

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1677,6 +1677,13 @@ function ThreadDetailBody(
16771677
key={props.selectedThread.latestRun?.runId}
16781678
thread={props.selectedThread}
16791679
environmentId={props.environmentId}
1680+
resetCredits={
1681+
props.serverConfig?.providers.find(
1682+
(provider) =>
1683+
provider.instanceId ===
1684+
props.selectedThread.runtime?.providerInstanceId,
1685+
)?.usageLimits?.resetCredits
1686+
}
16801687
/>
16811688
<ChildThreadApprovals
16821689
threadRef={props.selectedThreadDetailRef}

‎apps/mobile/src/features/threads/UsageLimitRecoveryCard.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ vi.mock("../../components/ui/Button", () => ({
3535
}));
3636
vi.mock("../../state/threads", () => ({ threadEnvironment: { updateMetadata: {} } }));
3737
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
38+
vi.mock("../usage/useResetCredit", () => ({ useResetCredit: vi.fn() }));
3839

3940
import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
4041

‎apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"
22
import { AsyncResult } from "effect/reactivity";
33
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
44
import { limitRecoveryOwnsSnooze } from "@t3tools/client-runtime/state/thread-execution";
5-
import type { EnvironmentId } from "@t3tools/contracts";
5+
import type {
6+
EnvironmentId,
7+
ProviderInstanceId,
8+
ServerProviderResetCredits,
9+
} from "@t3tools/contracts";
610
import {
711
CHATGPT_USAGE_LIMIT_CODE,
812
CHATGPT_USAGE_URL,
@@ -17,13 +21,17 @@ import { AppText as Text } from "../../components/ui/AppText";
1721
import { useDeadlinePassed } from "../../lib/clock";
1822
import { threadEnvironment } from "../../state/threads";
1923
import { useAtomCommand } from "../../state/use-atom-command";
24+
import { useResetCredit } from "../usage/useResetCredit";
2025

2126
export function UsageLimitRecoveryCard({
2227
thread,
2328
environmentId,
29+
resetCredits,
2430
}: {
2531
thread: EnvironmentThreadShell;
2632
environmentId: EnvironmentId;
33+
/** The limited account's banked reset credits, when it reports any. */
34+
resetCredits?: ServerProviderResetCredits | undefined;
2735
}) {
2836
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata);
2937
const [pending, setPending] = useState(false);
@@ -48,6 +56,7 @@ export function UsageLimitRecoveryCard({
4856
: resetAt;
4957
const [copied, setCopied] = useState(false);
5058
const [actionPending, setActionPending] = useState(false);
59+
const instanceId = thread.runtime?.providerInstanceId ?? null;
5160
const code = thread.runtime?.lastErrorCode;
5261
// OpenAI's partner guidelines specify the ChatGPT notice and its action.
5362
const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
@@ -59,6 +68,7 @@ export function UsageLimitRecoveryCard({
5968
!runId
6069
)
6170
return null;
71+
const canReset = instanceId !== null && (resetCredits?.availableCount ?? 0) > 0;
6272
const resetText = displayAt
6373
? `${canSchedule && scheduled ? "Resumes" : "Resets"} ${new Date(displayAt).toLocaleString(
6474
undefined,
@@ -155,9 +165,12 @@ export function UsageLimitRecoveryCard({
155165
? `Usage limit reached. ${resetText}`
156166
: "Usage limit reached. The provider did not report a reset time. Retry manually when your limit is available."}
157167
</Text>
158-
{chatGptLimit || canSchedule ? (
168+
{chatGptLimit || canSchedule || canReset ? (
159169
// The margins cancel the 44pt touch height so the links sit 8pt under the text.
160170
<View className="-mb-3 -mt-2 flex-row flex-wrap gap-x-4">
171+
{canReset && instanceId !== null ? (
172+
<ResetUsageAction environmentId={environmentId} instanceId={instanceId} />
173+
) : null}
161174
{chatGptLimit ? (
162175
<RecoveryAction
163176
label={action.label}
@@ -192,6 +205,25 @@ export function UsageLimitRecoveryCard({
192205
);
193206
}
194207

208+
function ResetUsageAction(props: {
209+
readonly environmentId: EnvironmentId;
210+
readonly instanceId: ProviderInstanceId;
211+
}) {
212+
const { canManageProviders, busy, status, confirm } = useResetCredit(props.environmentId, {
213+
instanceId: props.instanceId,
214+
});
215+
return (
216+
<>
217+
<RecoveryAction
218+
label={busy ? "Resetting…" : "Reset usage"}
219+
disabled={busy || !canManageProviders}
220+
onPress={confirm}
221+
/>
222+
{status ? <Text className="basis-full text-sm text-foreground">{status}</Text> : null}
223+
</>
224+
);
225+
}
226+
195227
function RecoveryAction(props: {
196228
readonly label: string;
197229
readonly role?: "button" | "link";

‎apps/mobile/src/features/usage/UsageLimitsSection.tsx‎

Lines changed: 2 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
import * as Dialog from "../../components/ui/Dialog";
21
import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
32
import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
43
import {
5-
AuthProvidersManageScope,
64
type EnvironmentId,
7-
type ProviderConsumeResetCreditOutcome,
85
type ProviderConsumeResetCreditInput,
96
type ServerProvider,
107
type ServerProviderResetCredits,
@@ -25,9 +22,6 @@ import { Linking, Pressable, View } from "react-native";
2522
import { AppText as Text } from "../../components/ui/AppText";
2623
import { ProviderIcon } from "../../components/ProviderIcon";
2724
import { environmentPresentations } from "../../state/presentation";
28-
import { serverEnvironment } from "../../state/server";
29-
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
30-
import { useAtomCommand } from "../../state/use-atom-command";
3125
import { useNowMinuteMs } from "../../lib/clock";
3226
import {
3327
environmentIdsKey,
@@ -36,6 +30,7 @@ import {
3630
refreshEnvironmentLimits,
3731
} from "./usageLimitsRefresh";
3832
import { usageProviderKind, useProviderColors } from "./usageProviders";
33+
import { useResetCredit } from "./useResetCredit";
3934

4035
const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
4136

@@ -220,13 +215,6 @@ export function AccountLimits(props: {
220215
);
221216
}
222217

223-
const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
224-
reset: "Reset applied. Your windows have cleared.",
225-
nothingToReset: "Nothing to reset right now.",
226-
noCredit: "No reset credit left.",
227-
alreadyRedeemed: "That credit was already redeemed.",
228-
};
229-
230218
export function ResetCredits(props: {
231219
readonly environmentId: EnvironmentId;
232220
readonly input: ProviderConsumeResetCreditInput;
@@ -235,12 +223,7 @@ export function ResetCredits(props: {
235223
readonly dense?: boolean;
236224
}) {
237225
const { environmentId, input, credits, now, dense = false } = props;
238-
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
239-
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
240-
reportFailure: false,
241-
});
242-
const [busy, setBusy] = useState(false);
243-
const [status, setStatus] = useState<string | null>(null);
226+
const { canManageProviders, busy, status, confirm } = useResetCredit(environmentId, input);
244227
if (dense && credits.availableCount === 0 && status === null) return null;
245228

246229
const expiresIn = credits.nextExpiresAt
@@ -253,35 +236,6 @@ export function ResetCredits(props: {
253236
expiresIn ? ` · next expires in ${expiresIn}` : ""
254237
}`;
255238

256-
const redeem = async () => {
257-
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
258-
setBusy(true);
259-
setStatus(null);
260-
const result = await consume({ environmentId, input });
261-
setBusy(false);
262-
if (result._tag === "Success") {
263-
setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
264-
return;
265-
}
266-
setStatus(
267-
"error" in result.cause && result.cause.error instanceof Error
268-
? result.cause.error.message
269-
: "Could not use the reset credit.",
270-
);
271-
};
272-
273-
const confirm = () => {
274-
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
275-
Dialog.alert(
276-
"Use a reset credit?",
277-
"This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
278-
[
279-
{ text: "Cancel", style: "cancel" },
280-
{ text: "Use credit", onPress: () => void redeem() },
281-
],
282-
);
283-
};
284-
285239
return (
286240
<View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
287241
<Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { createRef, useImperativeHandle } from "react";
2+
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
3+
import { act } from "react";
4+
import { createRoot } from "react-dom/client";
5+
import { expect, it, vi } from "vite-plus/test";
6+
7+
const mocks = vi.hoisted(() => ({ consume: vi.fn(), canManage: vi.fn() }));
8+
vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
9+
vi.mock("../../state/server", () => ({ serverEnvironment: { consumeResetCredit: {} } }));
10+
vi.mock("../../state/session", () => ({
11+
readEnvironmentScope: mocks.canManage,
12+
useEnvironmentScope: () => true,
13+
}));
14+
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.consume }));
15+
16+
import * as Dialog from "../../components/ui/Dialog";
17+
import { useResetCredit } from "./useResetCredit";
18+
19+
const environmentId = EnvironmentId.make("reset-environment");
20+
const input = { instanceId: ProviderInstanceId.make("codex") };
21+
const success = { _tag: "Success", value: { outcome: "reset" } } as const;
22+
type Result = typeof success | { readonly _tag: "Failure"; readonly cause: { error: Error } };
23+
24+
function setup() {
25+
mocks.consume.mockReset().mockResolvedValue(success);
26+
mocks.canManage.mockReset().mockReturnValue(true);
27+
vi.mocked(Dialog.alert).mockClear();
28+
const root = createRoot(document.createElement("div"));
29+
const ref = createRef<ReturnType<typeof useResetCredit>>();
30+
function Probe() {
31+
const value = useResetCredit(environmentId, input);
32+
useImperativeHandle(ref, () => value);
33+
return null;
34+
}
35+
act(() => root.render(<Probe />));
36+
return {
37+
get value() {
38+
if (ref.current === null) throw new Error("Reset-credit hook was not mounted");
39+
return ref.current;
40+
},
41+
[Symbol.dispose]: () => act(() => root.unmount()),
42+
};
43+
}
44+
45+
function approval() {
46+
const action = vi
47+
.mocked(Dialog.alert)
48+
.mock.lastCall?.[2]?.find((button) => button.text === "Use credit")?.onPress;
49+
if (action === undefined) throw new Error("Missing reset-credit confirmation");
50+
return action;
51+
}
52+
53+
it.each(["success", "failure", "rejection"] as const)(
54+
"coalesces overlapping approvals and permits a new attempt after %s",
55+
async (outcome) => {
56+
using fixture = setup();
57+
let resolve!: (value: Result) => void;
58+
let reject!: (reason: Error) => void;
59+
const promise = new Promise<Result>((complete, fail) => {
60+
resolve = complete;
61+
reject = fail;
62+
});
63+
const pending = { promise, resolve, reject };
64+
mocks.consume.mockReturnValueOnce(pending.promise);
65+
fixture.value.confirm();
66+
const first = approval();
67+
fixture.value.confirm();
68+
const second = approval();
69+
act(() => {
70+
first();
71+
second();
72+
});
73+
expect(mocks.consume).toHaveBeenCalledTimes(1);
74+
expect(mocks.consume).toHaveBeenCalledWith({ environmentId, input });
75+
expect(fixture.value.busy).toBe(true);
76+
const prompts = vi.mocked(Dialog.alert).mock.calls.length;
77+
fixture.value.confirm();
78+
expect(Dialog.alert).toHaveBeenCalledTimes(prompts);
79+
80+
await act(async () => {
81+
if (outcome === "rejection") pending.reject(new Error("Disconnected"));
82+
else if (outcome === "failure") {
83+
pending.resolve({ _tag: "Failure", cause: { error: new Error("Denied") } });
84+
} else pending.resolve(success);
85+
await pending.promise.catch(() => undefined);
86+
});
87+
expect(fixture.value.busy).toBe(false);
88+
expect(fixture.value.status).toBe(
89+
outcome === "success"
90+
? "Reset applied. Your windows have cleared."
91+
: outcome === "failure"
92+
? "Denied"
93+
: "Could not use the reset credit.",
94+
);
95+
await act(async () => {
96+
fixture.value.confirm();
97+
approval()();
98+
});
99+
expect(mocks.consume).toHaveBeenCalledTimes(2);
100+
expect(fixture.value.busy).toBe(false);
101+
},
102+
);
103+
104+
it("rechecks management permission after the confirmation opens", () => {
105+
using fixture = setup();
106+
fixture.value.confirm();
107+
const confirm = approval();
108+
mocks.canManage.mockReturnValue(false);
109+
act(() => confirm());
110+
expect(mocks.consume).not.toHaveBeenCalled();
111+
expect(fixture.value.busy).toBe(false);
112+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import {
2+
AuthProvidersManageScope,
3+
type EnvironmentId,
4+
type ProviderConsumeResetCreditInput,
5+
type ProviderConsumeResetCreditOutcome,
6+
} from "@t3tools/contracts";
7+
import { useRef, useState } from "react";
8+
9+
import * as Dialog from "../../components/ui/Dialog";
10+
import { serverEnvironment } from "../../state/server";
11+
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
12+
import { useAtomCommand } from "../../state/use-atom-command";
13+
14+
const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
15+
reset: "Reset applied. Your windows have cleared.",
16+
nothingToReset: "Nothing to reset right now.",
17+
noCredit: "No reset credit left.",
18+
alreadyRedeemed: "That credit was already redeemed.",
19+
};
20+
21+
/** Spending a credit asks for confirmation first because it cannot be undone. */
22+
export function useResetCredit(
23+
environmentId: EnvironmentId,
24+
input: ProviderConsumeResetCreditInput,
25+
) {
26+
const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
27+
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
28+
reportFailure: false,
29+
});
30+
const inFlight = useRef(false);
31+
const [busy, setBusy] = useState(false);
32+
const [status, setStatus] = useState<string | null>(null);
33+
34+
const redeem = async () => {
35+
if (inFlight.current || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
36+
inFlight.current = true;
37+
setBusy(true);
38+
setStatus(null);
39+
const result = await consume({ environmentId, input }).catch(() => null);
40+
inFlight.current = false;
41+
setBusy(false);
42+
if (result?._tag === "Success") {
43+
setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
44+
return;
45+
}
46+
setStatus(
47+
result !== null && "error" in result.cause && result.cause.error instanceof Error
48+
? result.cause.error.message
49+
: "Could not use the reset credit.",
50+
);
51+
};
52+
53+
const confirm = () => {
54+
if (inFlight.current || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
55+
Dialog.alert(
56+
"Use a reset credit?",
57+
"This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
58+
[
59+
{ text: "Cancel", style: "cancel" },
60+
{ text: "Use credit", onPress: () => void redeem() },
61+
],
62+
);
63+
};
64+
65+
return { canManageProviders, busy, status, confirm };
66+
}

‎apps/mobile/vite.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ const reactTests = [
5353
"src/features/connection/LinkedEnvironmentsSection.test.tsx",
5454
"src/features/devices/device-stream.browser.test.ts",
5555
"src/features/keyboard/keyboardControllerState.test.tsx",
56+
"src/features/usage/useResetCredit.test.tsx",
5657
];
5758

5859
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;

0 commit comments

Comments
 (0)