paseo-plugin-account-switcher 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +130 -0
- package/THIRD_PARTY_NOTICES.md +46 -0
- package/client/accounts.tsx +198 -0
- package/client/components.tsx +173 -0
- package/client/data.ts +47 -0
- package/client/format.ts +155 -0
- package/client/login.ts +48 -0
- package/client/runtime.ts +143 -0
- package/client/sign-in-state.ts +48 -0
- package/client/sign-in.tsx +108 -0
- package/client/switcher.tsx +115 -0
- package/client/web.ts +19 -0
- package/index.client.tsx +36 -0
- package/index.server.ts +30 -0
- package/licenses/iarna-toml-2.2.5.txt +14 -0
- package/licenses/paseo-0.8.0.txt +211 -0
- package/licenses/zod-4.6.5.txt +21 -0
- package/package.json +66 -0
- package/paseo-plugin.json +1 -0
- package/server/auth.ts +141 -0
- package/server/controller.ts +319 -0
- package/server/files.ts +17 -0
- package/server/integration.ts +152 -0
- package/server/launcher-artifact.ts +2 -0
- package/server/launcher-main.ts +80 -0
- package/server/login-process.ts +119 -0
- package/server/login.ts +167 -0
- package/server/paseo-api.ts +5 -0
- package/server/profiles.ts +138 -0
- package/server/store.ts +80 -0
- package/server/switching.ts +79 -0
- package/server/usage/README.md +89 -0
- package/server/usage/claude.ts +95 -0
- package/server/usage/codex.ts +79 -0
- package/server/usage/credential-hash.ts +4 -0
- package/server/usage/credentials.ts +18 -0
- package/server/usage/index.ts +225 -0
- package/server/usage/parsers.ts +63 -0
- package/shared/contracts.ts +63 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dutchakdev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Account Switcher for Paseo
|
|
2
|
+
|
|
3
|
+
Use multiple Claude and ChatGPT/Codex subscription accounts in Paseo. Choose an account for each agent, switch within an existing chat, and see limits across your saved accounts.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
- **Sign in from Paseo.** Add an account, finish the official provider sign-in, and return to your chat.
|
|
8
|
+
- **Switch per agent.** The account chip opens a dialog on desktop or a bottom sheet on mobile. Changes apply only when you choose **Apply**.
|
|
9
|
+
- **Keep your setup.** Profiles separate credentials while sharing provider settings, skills, and session history.
|
|
10
|
+
- **Track account limits.** See used and remaining percentages, reset times, and freshness for every reported window.
|
|
11
|
+
- **Use a default.** Choose the account used by new agents for each provider.
|
|
12
|
+
|
|
13
|
+
## Requirements
|
|
14
|
+
|
|
15
|
+
- **Paseo 0.8.x, 0.9.x, 0.10.x, or 0.11.x**, including beta releases, on a **macOS or Linux** daemon and on the connected client.
|
|
16
|
+
- **Node.js 22.12.0 or newer**, with npm.
|
|
17
|
+
- Official **Claude Code**, **Codex**, and **Paseo** CLIs available to the daemon. Both provider CLIs must be installed, even if you initially use only one.
|
|
18
|
+
- Claude or ChatGPT subscription authentication. API keys and custom authentication/provider overrides are unsupported.
|
|
19
|
+
|
|
20
|
+
The interface is in English. Reset dates use the viewing device's local time zone. See [installation](docs/installation.md) for remote hosts and [verification](docs/verification.md) for the scope of recorded testing.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
Install from npm on a daemon running Paseo 0.9 or newer:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
paseo plugin install npm:paseo-plugin-account-switcher --host 127.0.0.1:6767
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The npm package ships the generated launcher, so no build runs on the daemon.
|
|
31
|
+
Paseo 0.8 has no npm sources; install from Git there with
|
|
32
|
+
`paseo plugin install dutchakdev/paseo-plugin-account-switcher`, which downloads
|
|
33
|
+
the source and runs the manifest's dependency and build steps.
|
|
34
|
+
To review or develop the source first, use a local checkout:
|
|
35
|
+
|
|
36
|
+
Download or clone this repository onto the **daemon's machine**, then run these commands from its directory:
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm ci --ignore-scripts --legacy-peer-deps
|
|
40
|
+
npm run build
|
|
41
|
+
npm run typecheck
|
|
42
|
+
npm test
|
|
43
|
+
paseo plugin install "$PWD" --host 127.0.0.1:6767
|
|
44
|
+
paseo plugin ls account-switcher --host 127.0.0.1:6767
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
1. In Paseo, enable **Settings → Plugins → Enable plugins** if needed. Plugins are trusted, unsandboxed code with access to the daemon user's files, processes, credentials, and network.
|
|
48
|
+
2. Confirm that `account-switcher` is **running**. Open **Accounts** in the sidebar, or **Accounts and limits** in the Command Center.
|
|
49
|
+
3. Your existing **Current CLI · Claude** and **Current CLI · Codex** profiles appear automatically. They use the daemon's existing CLI authentication.
|
|
50
|
+
4. Select **Enable** in Accounts to turn on account switching. This saves the original provider commands and installs the plugin's launchers.
|
|
51
|
+
|
|
52
|
+
The example targets the local daemon at port `6767`. For a different daemon, follow the [host-specific installation steps](docs/installation.md#remote-daemons).
|
|
53
|
+
|
|
54
|
+
## Add an account
|
|
55
|
+
|
|
56
|
+
Select **Add**, choose a provider, name the account, and select **Add and sign in**. The official CLI runs in the background; the plugin opens a sign-in dialog without creating a terminal or workspace.
|
|
57
|
+
|
|
58
|
+
| Where you use Paseo | How to open sign-in |
|
|
59
|
+
| --- | --- |
|
|
60
|
+
| Desktop app | The dialog tries to copy the link. Paste it into your usual browser; **Copy link** retries copying. |
|
|
61
|
+
| Web or native mobile client | The dialog tries to open the browser. **Open browser** and **Copy link** remain available. |
|
|
62
|
+
|
|
63
|
+
If clipboard access is unavailable, expand **Show sign-in link** and copy its selectable text.
|
|
64
|
+
|
|
65
|
+
- **Claude:** finish on the provider's page. If it gives you an authorization code, paste the **complete code, including the part after `#`**, into **Authorization code** and select **Finish sign-in**.
|
|
66
|
+
- **Codex — Device code:** enter the displayed code on the provider's page. This is the choice for a phone or another computer. **Copy code** copies it.
|
|
67
|
+
- **Codex — Browser:** finish in a browser on the **daemon's computer**. The callback uses localhost. From another device, cancel and choose **Device code**.
|
|
68
|
+
|
|
69
|
+
The plugin verifies the identity and refreshes limits automatically. **Check sign-in** in the account's **⋯** menu provides a manual check. Enter passwords only on the provider's official page.
|
|
70
|
+
|
|
71
|
+
Closing the dialog leaves **Continue sign-in** on the account. **Cancel sign-in** stops the process before releasing the profile. While sign-in is active, the account cannot be applied, made the default, or deleted. A failed start leaves the account available for **Retry sign-in** without creating a duplicate. Plugin reloads stop pending sign-ins; start again afterward.
|
|
72
|
+
|
|
73
|
+
### Manage accounts
|
|
74
|
+
|
|
75
|
+
The **⋯** menu contains refresh, check sign-in, default, sign-in, rename, and delete actions. Account rows show identity, default status, and counts of current and pending agents.
|
|
76
|
+
|
|
77
|
+
Before signing in again, switch agents away from that profile. To delete a managed account, clear its default and all current or pending selections first. Deletion requires confirmation. **Archived agents retain their account binding for resume**; restore and switch them before deleting the account. System profiles cannot be deleted.
|
|
78
|
+
|
|
79
|
+
## Switch an existing chat
|
|
80
|
+
|
|
81
|
+
1. Select the account chip beside the message field to open **Account** over the current chat.
|
|
82
|
+
2. Under **Switch to**, choose a verified account from the **same provider**. The existing account stays marked **current**; the selected account is **pending**.
|
|
83
|
+
3. When the agent is idle and has no pending permission request, select **Apply “name”**.
|
|
84
|
+
|
|
85
|
+
You can select an account during a response, but it is **never applied automatically**. **Cancel selection** clears it. **All accounts** opens the full account list.
|
|
86
|
+
|
|
87
|
+
Apply reloads the agent through Paseo while preserving its native session ID. The plugin confirms the new account only after startup confirmation and successful reload. If a switch fails, it attempts to restore the previous account. **Account not confirmed** means the running account could not be established; select an account and apply again.
|
|
88
|
+
|
|
89
|
+
Different agents can use different accounts in parallel. Avoid sending from another client during Apply: Paseo's native reload has no atomic lock against a concurrent message, which could be interrupted.
|
|
90
|
+
|
|
91
|
+
## Read limits
|
|
92
|
+
|
|
93
|
+
Each account shows all reported limit windows, including zero usage. Measured windows show used and remaining percentages and a reset countdown. Expand details for exact local reset times, durations, fetch/check timestamps, and windows without data.
|
|
94
|
+
|
|
95
|
+
- Checks run every **5 minutes** in the background and every **60 seconds** while Accounts or the switcher is open.
|
|
96
|
+
- **Refresh** requests new data for one account; the header refresh action covers all accounts. Provider retry delays still apply.
|
|
97
|
+
- Color thresholds are **80%**, **95%**, and **100%** used. Missing data stays **No data**, never an invented zero.
|
|
98
|
+
- Failed requests can retain the last confirmed values as **stale**. Required sign-in, errors, and freshness remain visible.
|
|
99
|
+
- A passed reset time triggers a new check; it does not imply that usage is already zero.
|
|
100
|
+
|
|
101
|
+
Monitoring sends no model messages. The official CLIs own authentication and token refresh; a native Codex limits request may refresh its token. See [monitor details](server/usage/README.md) for scheduling, identity verification, and cache behavior.
|
|
102
|
+
|
|
103
|
+
## Update or remove
|
|
104
|
+
|
|
105
|
+
For a directory installation, update its source and run:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
npm ci --ignore-scripts --legacy-peer-deps
|
|
109
|
+
npm run build
|
|
110
|
+
npm run typecheck
|
|
111
|
+
npm test
|
|
112
|
+
paseo plugin reload account-switcher --host 127.0.0.1:6767
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Before disabling or removing the plugin, select **Disable** in Accounts to restore the original provider commands. Removal does not delete the separately stored account data. See [update and removal](docs/installation.md#update) for complete steps, Git installations, and recovery.
|
|
116
|
+
|
|
117
|
+
## Scope
|
|
118
|
+
|
|
119
|
+
This project supports manual, same-provider switching with subscription accounts. Automatic account rotation, API-key authentication, and Claude-to-Codex transfers are outside its scope. Provider authentication and limit formats can change with CLI versions; unsupported data is shown as unavailable.
|
|
120
|
+
|
|
121
|
+
Automated tests cover the implementation with synthetic accounts and provider responses. They do not establish real A → B → A switching, compaction, child-session behavior, or rewind for your accounts. Recorded checks and remaining live verification are in [verification](docs/verification.md).
|
|
122
|
+
|
|
123
|
+
## Documentation and contributions
|
|
124
|
+
|
|
125
|
+
- [Installation, updates, and troubleshooting](docs/installation.md)
|
|
126
|
+
- [Architecture, profile isolation, and stored data](docs/architecture.md)
|
|
127
|
+
- [Contributing and running checks](CONTRIBUTING.md)
|
|
128
|
+
- [Paseo plugin reference](https://paseo.sh/docs/plugins/reference)
|
|
129
|
+
|
|
130
|
+
Licensed under the [MIT License](LICENSE). See [third-party notices](THIRD_PARTY_NOTICES.md) for bundled dependencies.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
The standalone provider launcher contains code from the following packages.
|
|
4
|
+
The list comes from esbuild's output metafile, counting only dependencies that
|
|
5
|
+
contribute code after tree shaking. Development-only packages are not included
|
|
6
|
+
in this launcher list.
|
|
7
|
+
|
|
8
|
+
| Package | Bundled version | License | Full text |
|
|
9
|
+
| --- | --- | --- | --- |
|
|
10
|
+
| `@getpaseo/plugin` | 0.8.0 | Apache-2.0, with the upstream third-party component exception | [Paseo license](licenses/paseo-0.8.0.txt) |
|
|
11
|
+
| `@iarna/toml` | 2.2.5 | ISC | [TOML license](licenses/iarna-toml-2.2.5.txt) |
|
|
12
|
+
| `zod` | 4.6.5 | MIT | [Zod license](licenses/zod-4.6.5.txt) |
|
|
13
|
+
|
|
14
|
+
`npm run build` preserves esbuild's legal comments and embeds each complete
|
|
15
|
+
license, including copyright and permission notices, directly in the standalone
|
|
16
|
+
launcher's comment header. The generated `server/launcher-artifact.ts` contains
|
|
17
|
+
that header inside `LAUNCHER_SOURCE`; the launchers written to the daemon's data
|
|
18
|
+
directory retain it. No network request is needed during the build.
|
|
19
|
+
|
|
20
|
+
These dependencies are bundled and minified by esbuild. Their source code is
|
|
21
|
+
otherwise unmodified. The emitted Paseo code comes from the SDK's `rpc`,
|
|
22
|
+
`settings`, and `attachments` modules.
|
|
23
|
+
|
|
24
|
+
## License sources
|
|
25
|
+
|
|
26
|
+
- **Paseo:** copyright 2025-present Mohamed Boudra. The published SDK package
|
|
27
|
+
does not include a license file, so the complete file is copied from the
|
|
28
|
+
matching upstream [`v0.8.0` release](https://github.com/getpaseo/paseo/blob/v0.8.0/LICENSE),
|
|
29
|
+
commit [`b8e24677e12b226c7c38c1c3a40649daa9f1152f`](https://github.com/getpaseo/paseo/blob/b8e24677e12b226c7c38c1c3a40649daa9f1152f/LICENSE).
|
|
30
|
+
It retains the upstream statement that third-party components keep their own
|
|
31
|
+
licenses. That release has no separate root or plugin-package `NOTICE` file.
|
|
32
|
+
- **`@iarna/toml`:** copyright 2016 Rebecca Turner. The full text is copied
|
|
33
|
+
byte for byte from `@iarna/toml@2.2.5/LICENSE` in the installed npm package.
|
|
34
|
+
- **Zod:** copyright 2025 Colin McDonnell. The full text is copied byte for byte
|
|
35
|
+
from `zod@4.6.5/LICENSE` in the installed npm package.
|
|
36
|
+
|
|
37
|
+
## Updating dependencies
|
|
38
|
+
|
|
39
|
+
The build fails if an emitted package or version lacks a reviewed entry in
|
|
40
|
+
`scripts/build.mjs`. It also checks that the vendored TOML and Zod license texts
|
|
41
|
+
match the installed packages. When updating dependencies, inspect the new
|
|
42
|
+
license and attribution requirements, update `licenses/`, the reviewed versions
|
|
43
|
+
in the build script, and this document, then build and verify the launcher.
|
|
44
|
+
|
|
45
|
+
This document covers the bundled standalone launcher. Other packages installed
|
|
46
|
+
for development or supplied by Paseo remain subject to their own licenses.
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { useRpc, type PluginSurfaceProps } from "@getpaseo/plugin/client";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import { ScrollView, Text, View } from "react-native";
|
|
4
|
+
import { addAccount, cancelLogin, checkLogin, refreshUsage, removeAccount, renameAccount, setDefaultAccount, setIntegration, startLogin,
|
|
5
|
+
type Account, type AccountState, type LoginSession, type Provider, type UsageSnapshot } from "../shared/contracts";
|
|
6
|
+
import { body, Button, Field, heading, IconButton, InlineAction, muted, Notice, QuotaSummary, row, Segmented, StatusDot, toneColor } from "./components";
|
|
7
|
+
import { useAccountsData, useAction, useNow } from "./data";
|
|
8
|
+
import { accountStatus, errorMessage, providerName } from "./format";
|
|
9
|
+
import { accountAvailable, addOrResumeLogin, type LoginMode } from "./login";
|
|
10
|
+
import { SignInDialog, type SignInTarget } from "./sign-in";
|
|
11
|
+
import { closeSignInTarget, visibleSignInTarget } from "./sign-in-state";
|
|
12
|
+
|
|
13
|
+
export type AccountsProps = PluginSurfaceProps & { onChanged(): void; runtimeError?: string | null };
|
|
14
|
+
type SignInActions = { onStarted(account: Account, session: LoginSession): void; onResume(account: Account, sessionId: string): void };
|
|
15
|
+
|
|
16
|
+
const loginModes = [{ value: "device", label: "Device code" }, { value: "browser", label: "In browser" }] as const;
|
|
17
|
+
const providers = [{ value: "claude", label: providerName.claude }, { value: "codex", label: providerName.codex }] as const;
|
|
18
|
+
|
|
19
|
+
function AccountCard({ account, state, snapshot, now, theme, layout, host, onChanged, onStarted, onResume }: AccountsProps & SignInActions & {
|
|
20
|
+
account: Account; state: AccountState; snapshot: UsageSnapshot | undefined; now: number;
|
|
21
|
+
}) {
|
|
22
|
+
const rename = useRpc(renameAccount);
|
|
23
|
+
const remove = useRpc(removeAccount);
|
|
24
|
+
const setDefault = useRpc(setDefaultAccount);
|
|
25
|
+
const login = useRpc(startLogin);
|
|
26
|
+
const cancel = useRpc(cancelLogin);
|
|
27
|
+
const check = useRpc(checkLogin);
|
|
28
|
+
const refresh = useRpc(refreshUsage);
|
|
29
|
+
const action = useAction(host.id, onChanged);
|
|
30
|
+
const [panel, setPanel] = useState<"none" | "menu" | "rename" | "remove">("none");
|
|
31
|
+
const [label, setLabel] = useState(account.label);
|
|
32
|
+
const [notice, setNotice] = useState<string | null>(null);
|
|
33
|
+
const isDefault = state.defaults[account.provider] === account.id;
|
|
34
|
+
const inUse = state.bindings.filter((binding) => binding.currentAccountId === account.id).length;
|
|
35
|
+
const pending = state.bindings.filter((binding) => binding.pendingAccountId === account.id).length;
|
|
36
|
+
const managed = account.source === "managed";
|
|
37
|
+
const loginSession = account.login;
|
|
38
|
+
const status = accountStatus(account, snapshot);
|
|
39
|
+
const busy = action.isPending;
|
|
40
|
+
const needsLogin = managed && !loginSession && !accountAvailable(account);
|
|
41
|
+
const beginLogin = (mode?: LoginMode) => action.run(async () => {
|
|
42
|
+
setNotice(null); setPanel("none");
|
|
43
|
+
const result = await login({ accountId: account.id, ...(mode ? { mode } : {}) });
|
|
44
|
+
onStarted(account, result);
|
|
45
|
+
});
|
|
46
|
+
const loginButtons = (variant: "primary" | "secondary") => account.provider === "codex" ? <>
|
|
47
|
+
<Button theme={theme} variant={variant} disabled={busy} onPress={() => beginLogin("device")}>{needsLogin ? "Sign in with code" : "Sign in again with code"}</Button>
|
|
48
|
+
<Button theme={theme} disabled={busy} onPress={() => beginLogin("browser")}>{needsLogin ? "In browser" : "Sign in again in browser"}</Button>
|
|
49
|
+
</> : <Button theme={theme} variant={variant} disabled={busy} onPress={() => beginLogin()}>{needsLogin ? "Sign in" : "Sign in again"}</Button>;
|
|
50
|
+
const meta = [
|
|
51
|
+
account.email ?? (managed ? "separate profile" : "system CLI"),
|
|
52
|
+
isDefault ? "default for new agents" : null,
|
|
53
|
+
inUse ? `agents: ${inUse}` : null,
|
|
54
|
+
pending ? `pending: ${pending}` : null,
|
|
55
|
+
].filter(Boolean).join(" · ");
|
|
56
|
+
return <View accessibilityLabel={`Account ${account.label}`} style={{ borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1, borderRadius: 10, padding: layout.compact ? 10 : 12, gap: 10, minWidth: 0 }}>
|
|
57
|
+
<View style={{ flexDirection: "row", alignItems: "flex-start", gap: 8, flexWrap: "wrap" }}>
|
|
58
|
+
<View style={{ flex: 1, minWidth: 160, gap: 2 }}>
|
|
59
|
+
<Text selectable numberOfLines={1} style={heading(theme)}>{account.label}</Text>
|
|
60
|
+
<View style={{ flexDirection: "row", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
|
|
61
|
+
<StatusDot theme={theme} tone={status.tone} />
|
|
62
|
+
<Text style={{ ...muted(theme), color: status.tone === "muted" || status.tone === "success" ? theme.colors.foregroundMuted : toneColor(theme, status.tone) }}>{status.text}</Text>
|
|
63
|
+
<Text selectable numberOfLines={1} style={{ ...muted(theme), flexShrink: 1 }}>· {meta}</Text>
|
|
64
|
+
</View>
|
|
65
|
+
</View>
|
|
66
|
+
<View style={{ ...row, justifyContent: "flex-end" }}>
|
|
67
|
+
{loginSession ? <>
|
|
68
|
+
{"sessionId" in loginSession ? <Button theme={theme} variant="primary" onPress={() => onResume(account, loginSession.sessionId)}>Continue sign-in</Button> : null}
|
|
69
|
+
<Button theme={theme} disabled={busy} onPress={() => action.run(async () => { await cancel({ accountId: account.id, ...("sessionId" in loginSession ? { sessionId: loginSession.sessionId } : {}) }); setNotice("Sign-in canceled. You can start again."); })}>Cancel sign-in</Button>
|
|
70
|
+
</> : needsLogin ? loginButtons("primary") : null}
|
|
71
|
+
<IconButton theme={theme} icon="MoreHorizontal" label={`Actions for ${account.label}`} active={panel !== "none"} onPress={() => setPanel(panel === "none" ? "menu" : "none")} />
|
|
72
|
+
</View>
|
|
73
|
+
</View>
|
|
74
|
+
{loginSession ? <Notice theme={theme} tone="warning">
|
|
75
|
+
{"sessionId" in loginSession ? "Finish signing in in your browser. Status and limits will update automatically." : "A sign-in from an older version is still open. Cancel it, then sign in again to use the browser flow."}
|
|
76
|
+
</Notice> : null}
|
|
77
|
+
{panel === "menu" ? <View style={{ ...row, paddingTop: 2 }}>
|
|
78
|
+
<Button theme={theme} variant="ghost" disabled={busy || Boolean(loginSession)} onPress={() => action.run(() => refresh({ accountId: account.id }))}>Refresh limits</Button>
|
|
79
|
+
<Button theme={theme} variant="ghost" disabled={busy} onPress={() => action.run(async () => {
|
|
80
|
+
const result = await check({ accountId: account.id });
|
|
81
|
+
setNotice(result.authStatus === "ready" ? "Sign-in confirmed. You can now select this account for agents." : "Sign-in is not confirmed yet. Finish signing in in your browser, then check again.");
|
|
82
|
+
})}>Check sign-in</Button>
|
|
83
|
+
{isDefault
|
|
84
|
+
? <Button theme={theme} variant="ghost" disabled={busy} onPress={() => action.run(() => setDefault({ provider: account.provider, accountId: null }))}>Clear default</Button>
|
|
85
|
+
: <Button theme={theme} variant="ghost" disabled={busy || !accountAvailable(account)} onPress={() => action.run(() => setDefault({ provider: account.provider, accountId: account.id }))}>Default for new agents</Button>}
|
|
86
|
+
{managed && !needsLogin && !loginSession ? loginButtons("secondary") : null}
|
|
87
|
+
{managed ? <>
|
|
88
|
+
<Button theme={theme} variant="ghost" disabled={busy} onPress={() => { setLabel(account.label); setPanel("rename"); }}>Rename</Button>
|
|
89
|
+
<Button theme={theme} variant="danger" disabled={busy || Boolean(loginSession)} onPress={() => setPanel("remove")}>Remove</Button>
|
|
90
|
+
</> : null}
|
|
91
|
+
</View> : null}
|
|
92
|
+
{panel === "rename" ? <View style={row}>
|
|
93
|
+
<Field theme={theme} value={label} onChangeText={setLabel} maxLength={80} accessibilityLabel={`New name for ${account.label}`} placeholder="Account name" autoCapitalize="sentences" autoFocus
|
|
94
|
+
onSubmitEditing={() => label.trim() && action.run(async () => { await rename({ accountId: account.id, label: label.trim() }); setPanel("none"); })} />
|
|
95
|
+
<Button theme={theme} variant="primary" disabled={busy || !label.trim()} onPress={() => action.run(async () => { await rename({ accountId: account.id, label: label.trim() }); setPanel("none"); })}>Save</Button>
|
|
96
|
+
<Button theme={theme} variant="ghost" disabled={busy} onPress={() => setPanel("none")}>Cancel</Button>
|
|
97
|
+
</View> : null}
|
|
98
|
+
{panel === "remove" ? <View style={{ gap: 8 }}>
|
|
99
|
+
<Notice theme={theme} tone="danger">Remove “{account.label}” and its saved sign-in? {inUse || pending ? "An agent is using this account or has it pending: choose another account first." : "You will need to sign in again if you add it later."}</Notice>
|
|
100
|
+
<View style={row}>
|
|
101
|
+
<Button theme={theme} variant="danger" disabled={busy || Boolean(loginSession) || inUse > 0 || pending > 0} onPress={() => action.run(() => remove({ accountId: account.id }))}>Yes, remove</Button>
|
|
102
|
+
<Button theme={theme} variant="ghost" disabled={busy} onPress={() => setPanel("none")}>Keep account</Button>
|
|
103
|
+
</View>
|
|
104
|
+
</View> : null}
|
|
105
|
+
{notice ? <Notice theme={theme}>{notice}</Notice> : null}
|
|
106
|
+
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
107
|
+
<QuotaSummary theme={theme} snapshot={snapshot} now={now} compact={layout.compact}
|
|
108
|
+
onRefresh={loginSession ? undefined : () => action.run(() => refresh({ accountId: account.id }))} refreshing={busy} />
|
|
109
|
+
</View>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function AddAccountForm({ theme, host, onChanged, initialProvider, onClose, onStarted }: AccountsProps & Pick<SignInActions, "onStarted"> & { initialProvider: Provider; onClose(): void }) {
|
|
113
|
+
const add = useRpc(addAccount);
|
|
114
|
+
const login = useRpc(startLogin);
|
|
115
|
+
const action = useAction(host.id, onChanged);
|
|
116
|
+
const [provider, setProvider] = useState<Provider>(initialProvider);
|
|
117
|
+
const [label, setLabel] = useState("");
|
|
118
|
+
const [mode, setMode] = useState<LoginMode>("device");
|
|
119
|
+
// The account created by a failed first attempt; later submits only reopen its login.
|
|
120
|
+
const [created, setCreated] = useState<Account | null>(null);
|
|
121
|
+
const busy = action.isPending;
|
|
122
|
+
const submit = () => (created || label.trim()) && action.run(async () => {
|
|
123
|
+
let account = created;
|
|
124
|
+
const session = await addOrResumeLogin({ provider, label: label.trim(), mode, created }, { add, start: login, onCreated: value => { account = value; setCreated(value); } });
|
|
125
|
+
// Failed authorization startup keeps the created account available for retry.
|
|
126
|
+
onClose();
|
|
127
|
+
if (account) onStarted(account, session);
|
|
128
|
+
});
|
|
129
|
+
return <View style={{ gap: 10, padding: 12, backgroundColor: theme.colors.surface1, borderColor: theme.colors.border, borderWidth: 1, borderRadius: 10 }}>
|
|
130
|
+
<View style={row}>
|
|
131
|
+
<Segmented<Provider> theme={theme} label="Provider" value={provider} options={providers} onChange={setProvider} disabled={busy || Boolean(created)} />
|
|
132
|
+
{provider === "codex" ? <Segmented<LoginMode> theme={theme} label="ChatGPT sign-in method" value={mode} options={loginModes} onChange={setMode} disabled={busy} /> : null}
|
|
133
|
+
</View>
|
|
134
|
+
<View style={row}>
|
|
135
|
+
{created ? <Text style={{ ...body(theme), flexGrow: 1, minWidth: 160 }}>Account “{created.label}” was added, but sign-in has not started.</Text>
|
|
136
|
+
: <Field theme={theme} value={label} onChangeText={setLabel} maxLength={80} placeholder="Name, e.g. Personal" accessibilityLabel="New account name" autoFocus onSubmitEditing={submit} />}
|
|
137
|
+
<Button theme={theme} variant="primary" disabled={busy || (!created && !label.trim())} onPress={submit}>{busy ? "Starting sign-in…" : created ? "Retry sign-in" : "Add and sign in"}</Button>
|
|
138
|
+
<Button theme={theme} variant="ghost" disabled={busy} onPress={onClose}>{created ? "Close" : "Cancel"}</Button>
|
|
139
|
+
</View>
|
|
140
|
+
<Text style={muted(theme)}>{created ? "The account is already listed below. You can also start sign-in from its card." : provider === "codex" ? mode === "device" ? "Open the sign-in link on any device and enter the code shown here." : "Browser sign-in must finish on the daemon’s computer. Use Device code for another device." : "Continue in your browser, or copy the sign-in link to another device."}</Text>
|
|
141
|
+
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
142
|
+
</View>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function AccountsSurface(props: AccountsProps) {
|
|
146
|
+
const { theme, layout, host, runtimeError, onChanged } = props;
|
|
147
|
+
const { accounts, usage } = useAccountsData(host.id);
|
|
148
|
+
const refresh = useRpc(refreshUsage);
|
|
149
|
+
const integration = useRpc(setIntegration);
|
|
150
|
+
const action = useAction(host.id, onChanged);
|
|
151
|
+
const now = useNow();
|
|
152
|
+
const [adding, setAdding] = useState<Provider | null>(null);
|
|
153
|
+
const [signIn, setSignIn] = useState<SignInTarget | null>(null);
|
|
154
|
+
const visibleSignIn = visibleSignInTarget(signIn, host.id);
|
|
155
|
+
const onStarted = (account: Account, session: LoginSession) => setSignIn({ account, hostId: host.id, sessionId: session.id, initial: session, autoOpen: true });
|
|
156
|
+
const onResume = (account: Account, sessionId: string) => setSignIn({ account, hostId: host.id, sessionId, autoOpen: false });
|
|
157
|
+
const state = accounts.data;
|
|
158
|
+
const enabled = state?.integration.enabled ?? false;
|
|
159
|
+
const toggleIntegration = () => action.run(() => integration({ enabled: !enabled }));
|
|
160
|
+
return <><ScrollView style={{ flex: 1, backgroundColor: theme.colors.surface0 }} contentContainerStyle={{ padding: layout.compact ? 12 : 20, gap: 12, width: "100%", maxWidth: 960, alignSelf: "center", paddingBottom: 40 }} keyboardShouldPersistTaps="handled">
|
|
161
|
+
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
|
|
162
|
+
<View style={{ flex: 1, minWidth: 0, gap: 1 }}>
|
|
163
|
+
<Text style={{ color: theme.colors.foreground, fontSize: layout.compact ? 20 : 22, fontWeight: "700" }}>Accounts</Text>
|
|
164
|
+
{state ? <View style={{ flexDirection: "row", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
|
|
165
|
+
<Text style={muted(theme)}>Accounts: {state.accounts.length} · switching {enabled ? "on" : "off"}</Text>
|
|
166
|
+
{enabled ? <InlineAction theme={theme} disabled={action.isPending} onPress={toggleIntegration}>Disable</InlineAction> : null}
|
|
167
|
+
</View> : <Text style={muted(theme)}>{accounts.isPending ? "Loading…" : "Data unavailable"}</Text>}
|
|
168
|
+
</View>
|
|
169
|
+
<IconButton theme={theme} icon="RefreshCw" label="Refresh all limits" disabled={action.isPending} onPress={() => action.run(() => refresh({}))} />
|
|
170
|
+
<Button theme={theme} variant="primary" disabled={action.isPending} onPress={() => setAdding(adding ? null : "claude")}>{adding ? "Close" : "Add"}</Button>
|
|
171
|
+
</View>
|
|
172
|
+
{state && !enabled ? <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
|
|
173
|
+
<View style={{ flex: 1, minWidth: 200 }}><Notice theme={theme} tone="warning">Account switching in the composer is off: agents use the system CLI.</Notice></View>
|
|
174
|
+
<Button theme={theme} disabled={action.isPending} onPress={toggleIntegration}>Enable</Button>
|
|
175
|
+
</View> : null}
|
|
176
|
+
{state?.integration.error ? <Notice theme={theme} tone="danger">{state.integration.error}</Notice> : null}
|
|
177
|
+
{runtimeError ? <Notice theme={theme} tone="danger">{runtimeError}</Notice> : null}
|
|
178
|
+
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
179
|
+
{accounts.error ? <Notice theme={theme} tone="danger">Could not refresh accounts: {errorMessage(accounts.error)}</Notice> : null}
|
|
180
|
+
{usage.error ? <Notice theme={theme} tone="danger">Could not refresh limits: {errorMessage(usage.error)}</Notice> : null}
|
|
181
|
+
{adding ? <AddAccountForm key={adding} {...props} initialProvider={adding} onStarted={onStarted} onClose={() => setAdding(null)} /> : null}
|
|
182
|
+
{state ? (["claude", "codex"] as const).map((provider) => {
|
|
183
|
+
const group = state.accounts.filter((account) => account.provider === provider);
|
|
184
|
+
return <View key={provider} style={{ gap: 8 }}>
|
|
185
|
+
<View style={{ flexDirection: "row", alignItems: "baseline", gap: 6, paddingTop: 4 }}>
|
|
186
|
+
<Text accessibilityRole="header" style={heading(theme)}>{providerName[provider]}</Text>
|
|
187
|
+
<Text style={muted(theme)}>{group.length}</Text>
|
|
188
|
+
</View>
|
|
189
|
+
{group.map((account) => <AccountCard key={account.id} {...props} account={account} state={state} snapshot={usage.data?.accounts.find((item) => item.accountId === account.id)} now={now} onStarted={onStarted} onResume={onResume} />)}
|
|
190
|
+
{!group.length ? <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
|
191
|
+
<Text style={muted(theme)}>No accounts.</Text>
|
|
192
|
+
<InlineAction theme={theme} onPress={() => setAdding(provider)}>Add</InlineAction>
|
|
193
|
+
</View> : null}
|
|
194
|
+
</View>;
|
|
195
|
+
}) : null}
|
|
196
|
+
{state ? <Text style={{ ...muted(theme), paddingTop: 4 }}>Limits refresh every minute while this panel is open and every 5 minutes in the background. The default account applies to new agents.</Text> : null}
|
|
197
|
+
</ScrollView>{visibleSignIn ? <SignInDialog key={visibleSignIn.sessionId} {...props} target={visibleSignIn} onClose={() => setSignIn(current => closeSignInTarget(current, visibleSignIn, host.id))} /> : null}</>;
|
|
198
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { PluginTheme } from "@getpaseo/plugin";
|
|
2
|
+
import { Icon } from "@getpaseo/plugin/client/react-native";
|
|
3
|
+
import { useState, type ReactNode } from "react";
|
|
4
|
+
import { Pressable, Text, TextInput, View, type TextInputProps, type TextStyle, type ViewStyle } from "react-native";
|
|
5
|
+
import type { UsageSnapshot, UsageWindow } from "../shared/contracts";
|
|
6
|
+
import { freshness, localDate, percent, quotaTone, remainingPercent, shortCountdown, splitWindows, targetSlop, windowIsExpired, windowLength, type Tone } from "./format";
|
|
7
|
+
|
|
8
|
+
export type ThemeProps = { theme: PluginTheme };
|
|
9
|
+
export const row: ViewStyle = { flexDirection: "row", alignItems: "center", flexWrap: "wrap", gap: 8 };
|
|
10
|
+
export const tabular: TextStyle = { fontVariant: ["tabular-nums"] };
|
|
11
|
+
export const muted = (theme: PluginTheme): TextStyle => ({ color: theme.colors.foregroundMuted, fontSize: 12, lineHeight: 17 });
|
|
12
|
+
export const body = (theme: PluginTheme): TextStyle => ({ color: theme.colors.foreground, fontSize: 13, lineHeight: 18 });
|
|
13
|
+
export const heading = (theme: PluginTheme): TextStyle => ({ color: theme.colors.foreground, fontSize: 15, lineHeight: 20, fontWeight: "600" });
|
|
14
|
+
|
|
15
|
+
export function toneColor(theme: PluginTheme, tone: Tone): string {
|
|
16
|
+
return tone === "success" ? theme.colors.statusSuccess : tone === "warning" ? theme.colors.statusWarning
|
|
17
|
+
: tone === "danger" ? theme.colors.statusDanger : theme.colors.foregroundMuted;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Keep the actual box tappable: hitSlop is clipped by a parent's bounds on native.
|
|
21
|
+
const hitSlop = targetSlop(44);
|
|
22
|
+
|
|
23
|
+
export function Button({ theme, children, onPress, disabled, variant = "secondary", label }: ThemeProps & {
|
|
24
|
+
children: ReactNode; onPress(): void; disabled?: boolean; variant?: "primary" | "secondary" | "ghost" | "danger"; label?: string;
|
|
25
|
+
}) {
|
|
26
|
+
const primary = variant === "primary";
|
|
27
|
+
const textColor = primary ? theme.colors.accentForeground : variant === "danger" ? theme.colors.statusDanger : theme.colors.foreground;
|
|
28
|
+
return <Pressable accessibilityRole="button" accessibilityLabel={label} accessibilityState={{ disabled: Boolean(disabled) }} hitSlop={hitSlop}
|
|
29
|
+
disabled={disabled} onPress={onPress} style={({ pressed }) => ({
|
|
30
|
+
minHeight: 44, paddingHorizontal: variant === "ghost" ? 8 : 12, borderRadius: 8, justifyContent: "center",
|
|
31
|
+
backgroundColor: primary ? theme.colors.accent : variant === "ghost" ? "transparent" : theme.colors.surface2,
|
|
32
|
+
borderWidth: variant === "ghost" ? 0 : 1, borderColor: primary ? theme.colors.accent : theme.colors.border,
|
|
33
|
+
opacity: disabled ? 0.45 : pressed ? 0.7 : 1,
|
|
34
|
+
})}>
|
|
35
|
+
<Text numberOfLines={1} style={{ color: textColor, fontSize: 13, fontWeight: "600", textAlign: "center" }}>{children}</Text>
|
|
36
|
+
</Pressable>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function IconButton({ theme, icon, label, onPress, disabled, active }: ThemeProps & {
|
|
40
|
+
icon: string; label: string; onPress(): void; disabled?: boolean; active?: boolean;
|
|
41
|
+
}) {
|
|
42
|
+
return <Pressable accessibilityRole="button" accessibilityLabel={label} accessibilityState={{ disabled: Boolean(disabled), expanded: active }}
|
|
43
|
+
hitSlop={hitSlop} disabled={disabled} onPress={onPress} style={({ pressed }) => ({
|
|
44
|
+
width: 44, height: 44, borderRadius: 8, alignItems: "center", justifyContent: "center",
|
|
45
|
+
backgroundColor: active ? theme.colors.surface2 : "transparent", opacity: disabled ? 0.45 : pressed ? 0.7 : 1,
|
|
46
|
+
})}>
|
|
47
|
+
<Icon name={icon} size={18} color={theme.colors.foreground} />
|
|
48
|
+
</Pressable>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Small text-only action inside a line of muted text. */
|
|
52
|
+
export function InlineAction({ theme, children, onPress, disabled }: ThemeProps & { children: ReactNode; onPress(): void; disabled?: boolean }) {
|
|
53
|
+
return <Pressable accessibilityRole="button" accessibilityState={{ disabled: Boolean(disabled) }} hitSlop={targetSlop(44, 6)} disabled={disabled} onPress={onPress}
|
|
54
|
+
style={({ pressed }) => ({ minHeight: 44, justifyContent: "center", opacity: disabled ? 0.45 : pressed ? 0.7 : 1 })}>
|
|
55
|
+
<Text style={{ color: theme.colors.foreground, fontSize: 12, fontWeight: "600" }}>{children}</Text>
|
|
56
|
+
</Pressable>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function Notice({ theme, children, tone = "muted" }: ThemeProps & { children: ReactNode; tone?: Tone }) {
|
|
60
|
+
const color = toneColor(theme, tone);
|
|
61
|
+
return <View accessibilityRole={tone === "danger" ? "alert" : undefined}
|
|
62
|
+
style={{ borderLeftWidth: 2, borderLeftColor: color, paddingLeft: 10, paddingVertical: 2 }}>
|
|
63
|
+
<Text selectable style={{ ...body(theme), color: tone === "muted" ? theme.colors.foregroundMuted : color }}>{children}</Text>
|
|
64
|
+
</View>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function StatusDot({ theme, tone }: ThemeProps & { tone: Tone }) {
|
|
68
|
+
return <View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: toneColor(theme, tone) }} />;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function Segmented<Value extends string>({ theme, value, options, onChange, disabled, label }: ThemeProps & {
|
|
72
|
+
value: Value; options: readonly { value: Value; label: string }[]; onChange(value: Value): void; disabled?: boolean; label: string;
|
|
73
|
+
}) {
|
|
74
|
+
return <View accessibilityRole="radiogroup" accessibilityLabel={label} style={{ flexDirection: "row", borderWidth: 1, borderColor: theme.colors.border, borderRadius: 8, overflow: "hidden", alignSelf: "flex-start" }}>
|
|
75
|
+
{options.map((option) => {
|
|
76
|
+
const selected = option.value === value;
|
|
77
|
+
return <Pressable key={option.value} accessibilityRole="radio" accessibilityState={{ selected, checked: selected, disabled: Boolean(disabled) }} disabled={disabled}
|
|
78
|
+
hitSlop={targetSlop(44, 0)} onPress={() => onChange(option.value)} style={({ pressed }) => ({
|
|
79
|
+
minHeight: 44, paddingHorizontal: 12, justifyContent: "center",
|
|
80
|
+
backgroundColor: selected ? theme.colors.surface2 : "transparent", opacity: disabled ? 0.45 : pressed ? 0.7 : 1,
|
|
81
|
+
})}>
|
|
82
|
+
<Text style={{ ...body(theme), fontWeight: selected ? "600" : "400" }}>{option.label}</Text>
|
|
83
|
+
</Pressable>;
|
|
84
|
+
})}
|
|
85
|
+
</View>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function Field({ theme, ...props }: ThemeProps & TextInputProps) {
|
|
89
|
+
return <TextInput placeholderTextColor={theme.colors.foregroundMuted} {...props}
|
|
90
|
+
style={{ ...body(theme), minHeight: 44, borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface0, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 8, flexGrow: 1, minWidth: 160 }} />;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function Disclosure({ theme, title, open, onToggle, children }: ThemeProps & { title: string; open: boolean; onToggle(): void; children: ReactNode }) {
|
|
94
|
+
return <View style={{ gap: 6 }}>
|
|
95
|
+
<Pressable accessibilityRole="button" accessibilityState={{ expanded: open }} hitSlop={targetSlop(44)} onPress={onToggle}
|
|
96
|
+
style={({ pressed }) => ({ flexDirection: "row", alignItems: "center", gap: 4, minHeight: 44, alignSelf: "flex-start", opacity: pressed ? 0.7 : 1 })}>
|
|
97
|
+
<Icon name={open ? "ChevronDown" : "ChevronRight"} size={14} color={theme.colors.foregroundMuted} />
|
|
98
|
+
<Text style={muted(theme)}>{title}</Text>
|
|
99
|
+
</Pressable>
|
|
100
|
+
{open ? children : null}
|
|
101
|
+
</View>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function Meter({ theme, used }: ThemeProps & { used: number | null }) {
|
|
105
|
+
const width = used === null || !Number.isFinite(used) ? 0 : Math.min(100, Math.max(0, used));
|
|
106
|
+
return <View accessibilityRole="progressbar" accessibilityValue={used === null ? { text: "Unknown" } : { min: 0, max: 100, now: width }}
|
|
107
|
+
style={{ height: 4, borderRadius: 2, overflow: "hidden", backgroundColor: theme.colors.surface2, flexGrow: 1 }}>
|
|
108
|
+
<View style={{ height: 4, width: `${width}%`, backgroundColor: toneColor(theme, quotaTone(used)) }} />
|
|
109
|
+
</View>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** One quota on one line: label · meter · used/left · countdown. Expired windows keep the last value and say so. */
|
|
113
|
+
export function QuotaWindowRow({ theme, quota, now }: ThemeProps & { quota: UsageWindow; now: number }) {
|
|
114
|
+
const tone = quotaTone(quota.usedPercent);
|
|
115
|
+
const expired = windowIsExpired(quota, now);
|
|
116
|
+
const unknown = quota.usedPercent === null || !Number.isFinite(quota.usedPercent);
|
|
117
|
+
return <View accessibilityLabel={`${quota.label}: ${percent(quota.usedPercent)} used, ${shortCountdown(quota.resetsAt, now)}`} style={{ gap: 3 }}>
|
|
118
|
+
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
|
|
119
|
+
<Text numberOfLines={1} style={{ ...body(theme), flexShrink: 1, minWidth: 56 }}>{quota.label}</Text>
|
|
120
|
+
<Text style={{ ...muted(theme), ...tabular, color: unknown ? theme.colors.foregroundMuted : toneColor(theme, tone), fontWeight: "600", marginLeft: "auto" }}>
|
|
121
|
+
{unknown ? "no data" : `${percent(quota.usedPercent)} · ${percent(remainingPercent(quota.usedPercent))} left`}
|
|
122
|
+
</Text>
|
|
123
|
+
</View>
|
|
124
|
+
<Meter theme={theme} used={quota.usedPercent} />
|
|
125
|
+
<Text style={{ ...muted(theme), ...tabular, fontSize: 11, lineHeight: 14, color: expired ? theme.colors.statusWarning : theme.colors.foregroundMuted }}>
|
|
126
|
+
{expired ? "reset time passed · last known data" : shortCountdown(quota.resetsAt, now)}
|
|
127
|
+
</Text>
|
|
128
|
+
</View>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function DetailLine({ theme, children }: ThemeProps & { children: ReactNode }) {
|
|
132
|
+
return <Text selectable style={{ ...muted(theme), ...tabular }}>{children}</Text>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Compact quota block: measured windows first, then one disclosure with the windows without data,
|
|
137
|
+
* exact reset times, quota lengths and fetch timestamps. Errors and freshness are always visible.
|
|
138
|
+
*/
|
|
139
|
+
export function QuotaSummary({ theme, snapshot, now, compact, onRefresh, refreshing }: ThemeProps & {
|
|
140
|
+
snapshot: UsageSnapshot | undefined; now: number; compact: boolean; onRefresh?: () => void; refreshing?: boolean;
|
|
141
|
+
}) {
|
|
142
|
+
const [open, setOpen] = useState(false);
|
|
143
|
+
const { known, unknown } = snapshot ? splitWindows(snapshot.windows) : { known: [], unknown: [] };
|
|
144
|
+
const fresh = freshness(snapshot, now);
|
|
145
|
+
const detailsTitle = unknown.length ? `${unknown.length} more without data · details` : "Details";
|
|
146
|
+
return <View style={{ gap: 8 }}>
|
|
147
|
+
{known.length ? <View style={{ flexDirection: "row", flexWrap: "wrap", gap: compact ? 8 : 10 }}>
|
|
148
|
+
{known.map((quota) => <View key={quota.id} style={{ flexGrow: 1, flexBasis: compact ? "100%" : "46%", minWidth: 0 }}>
|
|
149
|
+
<QuotaWindowRow theme={theme} quota={quota} now={now} />
|
|
150
|
+
</View>)}
|
|
151
|
+
</View> : snapshot && snapshot.status !== "needs_auth" ? <Text style={muted(theme)}>{snapshot.windows.length ? "The provider did not return limit values." : "The provider has not returned limit windows yet."}</Text> : null}
|
|
152
|
+
{snapshot?.error ? <Notice theme={theme} tone="danger">{snapshot.error}</Notice> : null}
|
|
153
|
+
<View style={{ ...row, gap: 10 }}>
|
|
154
|
+
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
|
155
|
+
<StatusDot theme={theme} tone={fresh.tone} />
|
|
156
|
+
<Text style={{ ...muted(theme), color: fresh.tone === "muted" ? theme.colors.foregroundMuted : toneColor(theme, fresh.tone) }}>{fresh.text}{snapshot?.plan ? ` · ${snapshot.plan}` : ""}</Text>
|
|
157
|
+
</View>
|
|
158
|
+
{onRefresh ? <InlineAction theme={theme} disabled={refreshing} onPress={onRefresh}>{refreshing ? "Refreshing…" : "Refresh"}</InlineAction> : null}
|
|
159
|
+
</View>
|
|
160
|
+
{snapshot ? <Disclosure theme={theme} title={detailsTitle} open={open} onToggle={() => setOpen(!open)}>
|
|
161
|
+
<View style={{ gap: 4, paddingLeft: 18 }}>
|
|
162
|
+
{snapshot.windows.map((quota) => <DetailLine key={quota.id} theme={theme}>
|
|
163
|
+
{quota.label}: {quota.usedPercent === null ? "no data" : `${percent(quota.usedPercent)} used`}
|
|
164
|
+
{quota.resetsAt ? ` · resets ${localDate(quota.resetsAt)}` : " · reset time unknown"}
|
|
165
|
+
{windowLength(quota.windowDurationMins) ? ` · period ${windowLength(quota.windowDurationMins)}` : ""}
|
|
166
|
+
</DetailLine>)}
|
|
167
|
+
<DetailLine theme={theme}>Fetched: {localDate(snapshot.fetchedAt)} · checked: {localDate(snapshot.checkedAt)}</DetailLine>
|
|
168
|
+
{snapshot.nextRetryAt ? <DetailLine theme={theme}>Next attempt: {localDate(snapshot.nextRetryAt)}</DetailLine> : null}
|
|
169
|
+
<DetailLine theme={theme}>Reset times use your local time zone.</DetailLine>
|
|
170
|
+
</View>
|
|
171
|
+
</Disclosure> : null}
|
|
172
|
+
</View>;
|
|
173
|
+
}
|
package/client/data.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { useRpc } from "@getpaseo/plugin/client";
|
|
2
|
+
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { useEffect, useRef, useState } from "react";
|
|
4
|
+
import { listAccounts, listUsage } from "../shared/contracts";
|
|
5
|
+
|
|
6
|
+
export const accountsKey = (hostId: string) => ["account-switcher", hostId, "accounts"] as const;
|
|
7
|
+
export const usageKey = (hostId: string) => ["account-switcher", hostId, "usage"] as const;
|
|
8
|
+
|
|
9
|
+
export function useAccountsData(hostId: string) {
|
|
10
|
+
const accountsRpc = useRpc(listAccounts);
|
|
11
|
+
const usageRpc = useRpc(listUsage);
|
|
12
|
+
const accounts = useQuery({ queryKey: accountsKey(hostId), queryFn: () => accountsRpc({}), refetchInterval: 5_000, retry: 1 });
|
|
13
|
+
// Each mounted surface/dialog renews the foreground lease; collection is throttled by the daemon.
|
|
14
|
+
const usage = useQuery({ queryKey: usageKey(hostId), queryFn: () => usageRpc({ visible: true }), refetchInterval: 30_000, retry: 1 });
|
|
15
|
+
return { accounts, usage };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function useNow() {
|
|
19
|
+
const [now, setNow] = useState(Date.now);
|
|
20
|
+
useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 15_000); return () => clearInterval(timer); }, []);
|
|
21
|
+
return now;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// A synchronous lock also blocks a second press before React renders mutation.isPending.
|
|
25
|
+
export function useAction(hostId: string, onChanged?: () => void) {
|
|
26
|
+
const cache = useQueryClient();
|
|
27
|
+
const lock = useRef(false);
|
|
28
|
+
const mutation = useMutation({
|
|
29
|
+
mutationFn: async (action: () => Promise<unknown>) => action(),
|
|
30
|
+
onSettled: async () => {
|
|
31
|
+
// Account creation can succeed before authorization startup fails.
|
|
32
|
+
try {
|
|
33
|
+
await Promise.all([
|
|
34
|
+
cache.invalidateQueries({ queryKey: accountsKey(hostId) }),
|
|
35
|
+
cache.invalidateQueries({ queryKey: usageKey(hostId) }),
|
|
36
|
+
]);
|
|
37
|
+
onChanged?.();
|
|
38
|
+
} finally { lock.current = false; }
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
const run = (action: () => Promise<unknown>) => {
|
|
42
|
+
if (lock.current) return;
|
|
43
|
+
lock.current = true;
|
|
44
|
+
mutation.mutate(action);
|
|
45
|
+
};
|
|
46
|
+
return { ...mutation, run };
|
|
47
|
+
}
|