diff --git a/.agents/skills/communication-style/SKILL.md b/.agents/skills/communication-style/SKILL.md new file mode 100644 index 00000000..d1760fb8 --- /dev/null +++ b/.agents/skills/communication-style/SKILL.md @@ -0,0 +1,81 @@ +--- +name: communication-style +description: Use it always. +author: poteto (pstack) +--- + +# Communication style + +Edit text to remove AI patterns and add human voice. + +## Process + +1. Scan for the patterns below. +2. Rewrite. Preserve meaning, match intended tone. +3. Add soul (see next section). +4. Self-audit: "What makes this obviously AI generated?" Fix remaining tells. + +## Adding soul + +Removing patterns is half the job. Sterile, voiceless writing is just as obvious. + +- **Have opinions.** React to facts instead of neutrally listing pros and cons. +- **Vary rhythm.** Short sentences. Then longer ones that take their time. Mix it up. +- **Acknowledge complexity.** "Impressive but also kind of unsettling" beats "impressive." +- **Use "I" when it fits.** First person isn't unprofessional. +- **Let some mess in.** Perfect structure looks machine-made. +- **Be specific.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am." + +## Patterns to detect and fix + +### Content + +1. **Puffery.** "pivotal moment", "testament to", "evolving landscape", "setting the stage for", "indelible mark", "deeply rooted". Cut puffery, state what happened. +2. **Name-dropping.** Listing media outlets without context. Pick one, say what was said. +3. **Superficial -ing phrases.** "highlighting...", "ensuring...", "reflecting...", "showcasing...", "fostering...". Delete or expand with real sources. +4. **Promotional language.** "nestled", "vibrant", "breathtaking", "groundbreaking", "renowned", "stunning", "must-visit". Use neutral descriptions. +5. **Vague attributions.** "Experts believe", "Industry reports suggest", "Some critics argue". Name the source or delete. +6. **Formulaic challenges.** "Despite challenges... continues to thrive." Replace with specific facts. + +### Language + +7. **AI vocabulary.** Additionally, crucial, delve, enduring, enhance, fostering, garner, interplay, intricate, landscape (abstract), pivotal, showcase, tapestry (abstract), testament, underscore, vibrant. Replace with plain words. +8. **Fancy ways to say "is".** "serves as", "stands as", "boasts", "features". Just say "is" or "has". +9. **"Not just X, but Y."** State the point directly instead. +10. **Rule of three.** Forcing ideas into groups of three. Use the natural number. +11. **Synonym cycling.** Protagonist, main character, central figure, hero all in one paragraph. Pick one, repeat it. +12. **False ranges.** "from X to Y" where X and Y aren't on a meaningful scale. List topics directly. + +### Style + +13. **Em dash overuse.** Avoid em dashes entirely. Use periods or commas only (no parentheses, no en dashes, no hyphen-as-dash substitutes). Em dashes are an AI tell, and reaching for parentheses instead just trades one tell for another. If a thought needs separation, end the sentence or use a comma. +14. **Colon overuse.** Colons are fine before a list or example. Not as mid-sentence connectors. "If you're coming from traditional automation: instead of registering event handlers, you describe conditions" adds nothing with the colon. Rewrite to let the point stand on its own without comparison framing. "Describing when the scheduler should fire works best as plain English." Same meaning, no crutch punctuation. +15. **Boldface overuse.** Don't bold every proper noun or acronym. +16. **Inline-header lists.** The tell is a bold label and colon that restates the line: "**Performance:** Performance improved...". Convert to prose. A bold lead-in that ends in a period, names the item, and is followed by genuinely new detail ("**Schema in TypeScript.** Tables live in one file.") is fine. +17. **Title case headings.** Use sentence case. +18. **Decorative emojis.** Remove from headings and bullets. +19. **Curly quotes.** Replace with straight quotes. + +### Communication artifacts + +20. **Chatbot phrases.** "I hope this helps!", "Let me know if...", "Of course!", "Certainly!", "Found the smoking gun!" Remove. +21. **Cutoff disclaimers.** "While specific details are limited..." Find sources or remove. +22. **Sycophantic tone.** "Great question! You're absolutely right!" Respond directly. + +### Filler + +23. **Filler phrases.** "In order to" becomes "To". "Due to the fact that" becomes "Because". "It is important to note that" gets deleted. +24. **Excessive hedging.** "could potentially possibly be argued that it might" becomes "may". +25. **Generic conclusions.** "The future looks bright." State specific plans or facts. + +### Jargon + +26. **Abstract metaphor nouns.** Substrate, wedge, vector, locus, vantage, nexus, primitive (as noun), harness (as metaphor), surface (as in "API surface"), bedrock, scaffolding (as metaphor), modality, paradigm, gold-plating, ratchet (as metaphor), evacuate (for moving code), endgame, north star, flywheel. These read as technical but usually have a plainer concrete word. "Substrate" becomes "base". "Wedge in" becomes "add". "Vector" becomes "way" or "method". "Gold-plating" becomes "more than the job needs". "Ratchet" becomes the mechanism's real name or "a limit that only tightens". "Evacuate" becomes "move out". "Endgame" becomes "the last phase". Pick the concrete word. + +### Plain speech + +27. **Say what it does, not how it feels.** "the database stays close at hand", "SQL you can read", "types that follow your schema" name a feeling. The fix names the mechanism or a number: "`.toSQL()` returns the exact string sent to the database", "a column rename fails the build". Ask what the sentence tells the reader to do or know, then write it. If you can't restate it as a concrete instruction, fact, or number, cut it. One more check: if the sentence could appear unchanged in another project's docs, it says nothing about this one. Cut it. +28. **Shorten or split dense sentences.** If the reader has to backtrack to parse a sentence, break it in two or drop clauses. One idea per sentence. +29. **Active voice.** Prefer it. Catch "is/are/was/were + past participle" and name the actor: "queries are validated" becomes "the compiler validates queries", "the file is parsed by the loader" becomes "the loader parses the file". Passive is fine only when the actor is unknown or genuinely doesn't matter. +30. **Cut adverbs, or use a stronger verb.** "runs quickly" becomes "is fast" or the number. "significantly improves" becomes the measured delta. An adverb propping up a weak verb means the verb is wrong. +31. **Prefer the plain word.** "utilize" becomes "use", "leverage" becomes "use", "facilitate" becomes "help", "numerous" becomes "many", "in the event that" becomes "if". The fancier synonym is rarely clearer. diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index 04fbeb9c..e82bbba0 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -1,12 +1,7 @@ name: pr-review on: - pull_request_target: - types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] - issue_comment: - types: [created] - pull_request_review_comment: - types: [created] + workflow_dispatch: concurrency: # PR conversation comments arrive as `issue_comment` events, so their PR number diff --git a/.gitignore b/.gitignore index 51ed5714..03d5f68f 100644 --- a/.gitignore +++ b/.gitignore @@ -68,5 +68,8 @@ data/ workspaces/ *.pid .worktrees/ + +# Marks a disposable clone dedicated to unattended maintenance tasks. +.maintenance-clone test-results/ artifacts/ diff --git a/.opencode/agent/reproduce-issue.md b/.opencode/agent/reproduce-issue.md index de21e373..640ee322 100644 --- a/.opencode/agent/reproduce-issue.md +++ b/.opencode/agent/reproduce-issue.md @@ -1,7 +1,7 @@ --- mode: primary hidden: true -model: opencode-go/deepseek-v4-flash +model: opencode-go/mimo-v2.5 color: "#c0392b" permission: edit: allow diff --git a/.opencode/agent/summarize.md b/.opencode/agent/summarize.md index 99db887e..c3cd2b21 100644 --- a/.opencode/agent/summarize.md +++ b/.opencode/agent/summarize.md @@ -1,7 +1,7 @@ --- mode: primary hidden: true -model: opencode-go/deepseek-v4-flash +model: opencode-go/mimo-v2.5 color: "#4f8f8f" permission: edit: deny diff --git a/.opencode/agent/triage.md b/.opencode/agent/triage.md index 4df9199a..314f874d 100644 --- a/.opencode/agent/triage.md +++ b/.opencode/agent/triage.md @@ -1,7 +1,7 @@ --- mode: primary hidden: true -model: opencode-go/deepseek-v4-flash +model: opencode-go/mimo-v2.5 color: "#c4920a" permission: edit: deny diff --git a/.opencode/commands/as-fixes.md b/.opencode/commands/as-fixes.md new file mode 100644 index 00000000..8a4d87fc --- /dev/null +++ b/.opencode/commands/as-fixes.md @@ -0,0 +1,399 @@ +--- +description: Create an anti-slop lint cleanup PR from the next generated batch +agent: build +--- + +You are working in the OpenChamber repository. + +Goal: reduce anti-slop Oxlint findings in a small, reviewable maintenance PR. + +This task can run unattended on a schedule, so it must be safe to start at any moment and must stop cleanly when there is nothing to do. + +First, verify the worktree is safe to use: + +`git status --porcelain` + +If the output is not empty, decide which of two situations you are in. + +If the repository root contains a `.maintenance-clone` marker file, this working copy is a disposable clone dedicated to unattended maintenance. Nothing in it is human work in progress, so leftover changes are debris from an earlier task that failed to clean up after itself. Recover the clone rather than stopping: + +``` +git checkout -- . +git clean -fd +git checkout main +git pull +``` + +Report exactly which files you discarded, then continue with the task. A failed predecessor must not be able to jam the pipeline for every later run. + +If the marker file is absent, this is a working copy a person uses. Stop immediately and report that the worktree has uncommitted changes. Do not stash, reset, discard, commit, or switch branches. + +Then run: + +`bun run deslop -- next-batch --min-issues 60 --max-issues 120` + +Use the command output as the source of truth for this task scope. + +If the output contains `NO BATCH AVAILABLE`, stop immediately and report the printed reason. Do not create a branch, do not create a pull request, and do not look for other work. Concurrency is already handled: the command excludes files claimed by other active batches and refuses to exceed the active-batch limit. + +Background: anti-slop is a vendored Oxlint plugin at `tools/oxlint/anti-slop/`, configured in `oxlint.config.ts`. It rejects low-evidence typing: unjustified type assertions, `unknown`/`object`/`Record` contracts, ad hoc `typeof` narrowing, conditional `{}` spreads, and module mocking. Fixing a finding means giving the code real type evidence, never hiding the symptom. + +Workflow: +- Before generating the batch, switch to `main` and pull the latest remote changes. +- Read the `next-batch` output carefully. +- Use the exact `Run ID`, `Batch name`, `Branch name`, and `PR title` printed by the command. +- Create the branch using the printed `Branch name`. +- Work only on the selected files listed in the batch output. +- Treat the selected files as complete-file scope. Do not cherry-pick only the first N findings. +- Read each selected file fully before editing it. These findings sit on type contracts, so a local edit can change behavior at a distant call site. +- Fix as many findings as practical in the selected files. Your default should be to fix selected findings, not to skip them. + +## What a good fix looks like + +Every finding is the same underlying complaint: the code claims less about a value than it actually knows. A good fix restores the missing knowledge. A bad fix hides the complaint while the knowledge stays missing. The rule cannot tell the difference, so you must. + +Before editing, answer one question for the value in question: where does it actually come from? There are only three answers, and each has one correct fix. + +1. It comes from code in this repository. The real type already exists somewhere upstream. Find it and use it. No parsing, no assertion. +2. It crosses an I/O boundary: HTTP response, `postMessage`, file contents, `localStorage`, a child process, the OpenCode SDK edge. Parse it once at that boundary, then let the parsed type flow onward untouched. + +On parsing style, follow local precedent and do not introduce a new one. `zod` is declared as a dependency but is not currently used in the source, so a maintenance PR is the wrong place to start spreading it. Unless the file or package you are editing already parses with a schema library, write a small local parse function that takes the raw input, returns the domain type or `undefined`, and lives next to the boundary it guards. If you believe a schema library is genuinely warranted, skip the finding and say so in the PR body instead of introducing the pattern yourself. +3. It is genuinely dynamic, such as a plugin registry keyed by arbitrary strings. Then keep the open key but make the value type precise, and say so in the contract's name. + +### `no-unsafe-dictionary-type` + +Bad, and the most common lazy fix. The shape is known; the annotation throws it away. + +```ts +type QuotaSnapshot = Record; + +function readLimit(snapshot: QuotaSnapshot) { + return snapshot.limit; +} +``` + +Good. Name the contract and state the fields the code actually reads. + +```ts +type QuotaSnapshot = { + limit: number; + used: number; + resetsAt: string; +}; + +function readLimit(snapshot: QuotaSnapshot) { + return snapshot.limit; +} +``` + +Also good, when keys really are open but values are not. + +```ts +type ProviderQuotas = Record; +``` + +Still bad, and does not count as a fix: + +```ts +type QuotaSnapshot = Record; +type QuotaSnapshot = { [key: string]: object }; +type QuotaSnapshot = Record; +``` + +The third one is the sneaky one. Widening to a union of primitives satisfies the rule without describing anything. If you cannot name the fields, that is a signal the value is unparsed I/O; go to the boundary and parse it. + +### `no-unknown-parameters`, `no-unknown-returns`, `no-unknown-type-aliases` + +Bad. The function accepts anything and immediately guesses. + +```ts +function applyThemeMessage(message: unknown) { + const theme = message as { themeId: string }; + setTheme(theme.themeId); +} +``` + +Good. Parse at the boundary; the domain function receives a real type. + +```ts +type ThemeMessage = { themeId: string }; + +function parseThemeMessage(data: MessageEvent["data"]): ThemeMessage | undefined { + if (data === null || typeof data !== "object") return undefined; + const themeId = Reflect.get(data, "themeId"); + return typeof themeId === "string" ? { themeId } : undefined; +} + +function applyThemeMessage(message: ThemeMessage) { + setTheme(message.themeId); +} + +window.addEventListener("message", (event) => { + const message = parseThemeMessage(event.data); + if (message === undefined) return; + applyThemeMessage(message); +}); +``` + +The parse function itself will still report `no-runtime-typeof` and `no-reflect-get`, because it is doing exactly what those rules describe. That is expected and acceptable: the checks are now concentrated in one named boundary function instead of scattered through domain logic, and the domain function above is genuinely typed. Report these remaining findings in the PR body rather than hiding them. Do not silence them with inline suppressions. + +Note what changed at runtime: a malformed message is now ignored instead of silently producing `undefined` deeper in the call stack. That is a deliberate behavior decision and it belongs in the PR body. Never introduce a throw on a path that previously degraded quietly. + +The `cause` convention is the single allowed exception: `unknown` is correct for an error cause. + +### `no-known-value-widening` + +Bad. The annotation erases the known keys, so callers lose autocomplete and typo safety. + +```ts +const settingsBySlug: Record = { + appearance: appearanceSection, + keybindings: keybindingsSection, +}; +``` + +Good. Keep inference and validate the shape. + +```ts +const settingsBySlug = { + appearance: appearanceSection, + keybindings: keybindingsSection, +} satisfies Record; +``` + +`satisfies` checks every value against the contract while preserving the literal keys. Reach for it before anything else here. + +### `no-chained-type-assertions` and `no-widen-then-assert` + +Bad. The precise type existed and was thrown away, then guessed back. + +```ts +const raw = loadSession() as unknown as SessionSnapshot; +``` + +Good. Fix the upstream contract so the round trip is unnecessary. + +```ts +const snapshot = loadSession(); +``` + +If `loadSession` genuinely returns something imprecise, that function is the real defect. Fix it there when it is inside the batch scope; if it is outside, make the minimal supporting change and say so in the PR body. + +### `require-safety-comment-for-type-assertion` + +The first move is always to delete the assertion, not to document it. Only a small minority of these findings deserve a comment. + +Bad, and an automatic rejection at review: + +```ts +// SAFETY: this is safe. +const session = value as Session; + +// SAFETY: value is a Session. +const session = value as Session; + +// SAFETY: required by TypeScript. +const session = value as Session; +``` + +These say nothing. A valid comment names the check that already ran and the line or function that ran it, so a reviewer can verify the claim without trusting you. + +Good: + +```ts +const parsed = sessionSchema.safeParse(payload); +if (!parsed.success) return undefined; +// SAFETY: sessionSchema.safeParse above confirmed every field of Session. +const session = parsed.data as Session; +``` + +If you cannot write such a sentence truthfully, you do not have an assertion problem, you have a missing check. Add the check. + +### `no-conditional-empty-object-spread` + +This one changes behavior more often than it looks, so read the consumer before editing. + +Bad: + +```ts +const body = { + sessionId, + ...(title !== undefined ? { title } : {}), +}; +``` + +Good, when the consumer distinguishes a missing key from an explicit `undefined`, which is true for anything serialized to JSON or merged over defaults: + +```ts +const body: CreateSessionBody = { sessionId }; +if (title !== undefined) body.title = title; +``` + +Good, when the consumer treats both the same: + +```ts +const body = { sessionId, title }; +``` + +Choosing wrongly here sends `"title": null` or drops a field on a real API call. If you cannot determine which behavior the consumer needs by reading it, skip the finding and say why. + +### `no-runtime-typeof` + +Bad. An ad hoc check in the middle of domain logic. + +```ts +function resolveHost(stored: unknown) { + if (typeof stored === "string") return stored; + return DEFAULT_HOST; +} +``` + +Good. Read and validate where the value enters the program, then branch on real domain values. + +```ts +function readStoredHost(): string { + const stored = localStorage.getItem(STORED_HOST_KEY); + return stored !== null && stored.length > 0 ? stored : DEFAULT_HOST; +} +``` + +Here the fix removed the check entirely, because `localStorage.getItem` already has a precise contract: `string | null`. The original `unknown` was self-inflicted. Look for this case first; it is more common than it seems. + +When a real check is unavoidable, keep it inside one named boundary function as shown above, and accept that the boundary function keeps its finding. What is not acceptable is spreading the same check across domain code, or renaming it into a type predicate so it reads as intentional while nothing was actually established. + +### `no-module-mocking` + +Bad. The test mocks a module and therefore tests the mock. + +```ts +mock.module("../lib/runtimeFetch", () => ({ runtimeFetch: async () => ({ ok: true }) })); +``` + +Good. Pass the dependency in, and let the test supply a real function. + +```ts +async function loadStatus(fetchStatus: () => Promise) { + return fetchStatus(); +} + +test("returns the fetched status", async () => { + const status = await loadStatus(async () => ({ ok: true })); + expect(status.ok).toBe(true); +}); +``` + +If introducing the seam would restructure production code well beyond the batch, skip the finding and say so. Do not fake a seam you do not believe in. + +## How to know your fix is real + +Before moving to the next finding, check all four: + +- The code now knows something it did not know before. If you only rearranged syntax, it is not a fix. +- No new `any`, no new assertion, no new broad union invented to satisfy the checker. +- If you added parsing, you decided explicitly what happens on invalid input, and that decision is written in the PR body. +- If you changed a type used elsewhere, you searched for its call sites and updated them, rather than casting at the call site. + +Handle findings deliberately instead of skipping them: for parsing work, add the smallest schema that covers the fields actually used; for contract changes, follow call sites with search and update them; for tests, prefer real seams over widened fixtures. + +## Finish the file + +A selected file is finished when it has zero anti-slop findings for the enabled rules, or when every remaining finding has an individual, specific reason to stay. + +This matters beyond tidiness. A file left half-fixed will be selected again by a later batch, producing a second pull request over the same file, with its own template, its own review, and its own merge. Every finding you defer costs the repository owner a future review cycle. Treat "I fixed the easy half" as an incomplete task, not a delivery. + +So, before you consider a selected file done: + +- Re-run `bun run deslop -- file ` and read what is left. +- If findings remain, they must be the genuinely hard ones, and you must be able to explain each one specifically. "Requires a broader refactor" is only acceptable when you name the refactor, the module boundary it crosses, and why doing it here would make the change unreviewable. +- A group of findings sharing one root cause counts as one reason, and that root cause is usually worth fixing. If eleven findings in a file all come from one untyped parser, fixing that parser is the point of the batch, not a reason to skip. +- Leaving more than roughly a quarter of a file's findings behind means you have not finished. Either finish them or explain, per group, why the file was a bad selection in the first place. + +Skip a finding when the fix would require unclear behavior changes, when the change would be so large that the pull request stops being reviewable, or when the only way you can see to close it is one of the forbidden patterns. That last case is not a loophole, it is the required outcome: an honest skip is always better than a laundered fix, and choosing the forbidden pattern to satisfy "finish the file" is the worse failure of the two. Ordinary difficulty, on its own, is still not a reason. If skipped, give the specific reason in the PR body under `## Non-goals`. + +### When the whole file is an external-data boundary + +Some files exist to receive data from outside the program: provider APIs, quota endpoints, extension host messages, configuration on disk. In such a file, most or all findings can share one root cause, and the honest fix is a real parsed boundary with named contracts, which is a substantial piece of work rather than a lint cleanup. + +Recognize this early, before editing. Read the file first and ask whether closing its findings means designing a data contract that does not exist yet. If it does, choose one of two outcomes, and never a third: + +- Do the work properly for a coherent part of the file: define the contract for one provider, one endpoint, or one message, parse it at its boundary, and leave the rest with a clear explanation of the remaining root cause. A correct partial fix with a named boundary is a good pull request. +- Conclude that the file is a poor batch selection, abort per "Aborting cleanly", and say in your report that the file needs a deliberate data-contract change rather than an unattended cleanup. + +What you must not do is invent a generic JSON contract to make the findings disappear. Generic record types, primitive unions, and `unknown`-based aliases over external data are exactly the patterns these rules exist to reject, and reintroducing them under time pressure defeats the purpose of the whole task. + +Hard prohibitions. Each of these makes the lint output greener while making the code worse, and each is grounds for rejecting the whole PR: +- Do not disable, downgrade, or ignore anti-slop rules, in configuration or with inline comments. +- Do not add `any`, widen a type, or add an assertion in order to satisfy a rule. +- Do not write a generic or placeholder `// SAFETY:` comment. A comment that does not name a real, already-performed check is worse than the original finding. +- Do not invent a union of primitives to escape a dictionary rule. +- Do not move a rejected `typeof` check into a hand-written type predicate to get it out of the linter's way. +- Do not delete code, tests, or fields to make a finding disappear. +- Do not rename a symbol solely to dodge `no-shape-in-symbol-names`; rename it to what it actually is. +- Do not introduce a throw where the previous code degraded quietly. A parse failure on a path that used to fall back must keep falling back. +- Do not introduce a schema library, a new utility module, or a new architectural pattern as part of a lint cleanup. +- Do not edit `oxlint.config.ts` or `tools/oxlint/anti-slop/`. +- Do not edit `CHANGELOG.md`, package versions, or release metadata. This is internal maintenance with no user-facing change. +- Do not fix findings outside the selected files. + +## Aborting cleanly + +You may reach a point where the batch cannot be completed correctly: validation keeps failing, or the only remaining way to close the findings is a pattern this task forbids. Stopping there is the right decision. Stopping there and walking away from a modified working copy is not. + +Whatever edits exist in the working copy at that moment are your own, made minutes ago in this session. They are not human work in progress, and nothing is lost by removing them. Leaving them behind jams every scheduled run that follows, because those runs correctly refuse to operate on a dirty worktree. + +So when you abort, in this order: + +1. Revert every file you modified: `git checkout -- `, plus `git clean -fd` for files you created. Verify with `git status --porcelain` that the result is empty. +2. Release the claim so the files return to the pool: ``bun run deslop -- release --run ``. +3. Return to `main`. +4. Report what you attempted, precisely why you stopped, and confirm that both the worktree is clean and the claim is released. + +Never leave a partially fixed working copy as a message to the next run. If a file resists a correct fix, that belongs in your report, not on disk. + +After edits, run: + +`bun run deslop -- check-batch --run ` + +Then validate the packages you actually touched, not the whole workspace. For each affected package run its own checks, for example: + +`bun run --cwd packages/ui type-check` + +`bun run --cwd packages/ui lint` + +`bun run --cwd packages/ui test` + +Workspace-wide `bun run type-check` and `bun run lint` are CI's job. Run them locally only when a change crosses package boundaries or touches shared contracts. + +For files that TypeScript does not cover, such as server or CLI JavaScript, run the focused tests for that surface instead, for example `bun run --cwd packages/web test`. + +Validation and delivery: +- Confirm selected files have fewer findings than before. +- Confirm `Findings outside selected files delta` is not positive. If it is, you introduced new findings elsewhere; fix them before continuing. +- If validation fails, fix failures only if the fixes stay within the task scope. Otherwise stop and report the blocker. +- Commit the changes with a concise message. +- Push the branch. +- Create exactly one PR with `gh pr create` using the exact printed `PR title`. +- After the PR is created, switch back to `main` and pull the latest remote changes again. + +PR requirements. The repository has a mandatory pull request template at `.github/PULL_REQUEST_TEMPLATE.md`, and `AGENTS.md` requires it to be completed with concrete evidence for the final PR HEAD. Read the template and `CONTRIBUTING.md` before writing the description. Use every template heading, in the template's order, and do not invent replacement headings. Fill each section as follows. + +- Use the exact printed `PR title`. +- `## Intent`: state that this is an unattended maintenance batch, name the `Run ID`, `Batch name`, and `Branch name`, and say what behavior changes. When nothing observable changes, say so explicitly rather than leaving it implied. +- `## Non-goals`: the findings left unfixed in the selected files, findings elsewhere in the repository, and any refactor you deliberately did not start. Give the reason for each, not just the count. +- `## Affected surfaces`: the packages, runtimes, user-visible states, and persisted or external contracts the diff reaches. Name every runtime the changed code runs in, and explain why an apparently applicable runtime is unaffected. +- `## Repository guidance`: fill the table. List the `AGENTS.md` rules you followed, every project skill that matched the change, required skill references you read, and the nearest `README.md` or `DOCUMENTATION.md` for the touched modules. For each row explain why it applies and how the change complies. Do not list filenames without explanation. +- `## Validation`: fill the table with the exact commands you ran and their results, including `check-batch` and every package-scoped type-check, lint, and test command, naming the packages. Record failures honestly, including pre-existing failures unrelated to this PR, and say which checks you did not run. Do not claim runtime behavior from type-check or lint alone. +- `## Visual evidence`: these PRs usually have no visible change, so explain concretely why the diff cannot affect rendered behavior. If anything user-visible did change, attach before/after evidence for the affected states. +- `## Risks and failure behavior`: cover what breaks if a change is wrong, how to roll it back, and any compatibility, data, performance, or cross-runtime concern. This is where every behavior-affecting decision belongs: each parsing decision you introduced and what now happens on invalid input, each `// SAFETY:` comment you added with the invariant it documents, and any change to whether an object key is present. State "None identified" only with a concrete reason. + +Add a `## Manual testing recommendations` section after the template sections, with focused checks for the changed behavior, based on the selected files and actual edits. Type-contract changes can alter runtime behavior at call sites, so name the affected surfaces concretely. + +Also state, inside `## Intent`, the selected files and how many findings `check-batch` reports as fixed and remaining. + +Constraints: +- Keep the PR small and reviewable. +- Do not auto-merge. +- Do not modify unrelated files except minimal supporting changes required by selected-file fixes. +- Do not run broad formatting. +- Leave the batch's run directory intact after creating the PR. `next-batch` prints its location. That directory is both the handoff for the review follow-up task and the claim that stops another batch, including the React Doctor pipeline, from touching the same files. Deleting it early lets a parallel batch collide with this PR. Never delete it by hand; use `bun run deslop -- release --run `. +- If you stop before creating a PR for any reason, release the claim with `bun run deslop -- release --run ` so the files return to the pool. diff --git a/.opencode/commands/as-follow-up.md b/.opencode/commands/as-follow-up.md new file mode 100644 index 00000000..c7877b7e --- /dev/null +++ b/.opencode/commands/as-follow-up.md @@ -0,0 +1,83 @@ +--- +description: Follow up on an anti-slop PR by addressing review feedback +agent: build +--- + +You are working in the OpenChamber repository. + +Goal: follow up on an existing anti-slop maintenance PR, address Greptile/review bot feedback, and clean up the local batch handoff files when done. + +This task can run unattended on a schedule, so it must be safe to start at any moment and must stop cleanly when there is nothing to do. + +First, verify the worktree is safe to use: + +`git status --porcelain` + +If the output is not empty, decide which of two situations you are in. + +If the repository root contains a `.maintenance-clone` marker file, this working copy is a disposable clone dedicated to unattended maintenance. Nothing in it is human work in progress, so leftover changes are debris from an earlier task that failed to clean up after itself. Recover the clone rather than stopping: + +``` +git checkout -- . +git clean -fd +git checkout main +git pull +``` + +Report exactly which files you discarded, then continue with the task. A failed predecessor must not be able to jam the pipeline for every later run. + +If the marker file is absent, this is a working copy a person uses. Stop immediately and report that the worktree has uncommitted changes. Do not stash, reset, discard, commit, or switch branches. + +List the active batches: + +`bun run deslop -- active` + +The listing may include batches owned by the React Doctor pipeline; those are shown as `[pipeline rd]`. Never touch them. + +Workflow: +- If there are no active batches, stop and report that there is nothing to follow up. +- Each active batch corresponds to one open PR. Read its `batch.json` for `runId`, `branchName`, `batchName`, `prTitle`, and selected files. +- Use `gh` to find the open PR for each batch branch. +- Work on the oldest batch that has an open PR with unaddressed feedback. If several qualify, handle exactly one and leave the rest. +- If a batch's PR was already merged or closed, do not treat it as follow-up work. Release its claim with `bun run deslop -- release --run ` so its files return to the pool, then continue looking. +- If no batch has an open PR with actionable feedback, stop and report that. +- Switch to the batch branch using the exact `branchName`. +- Pull or update the branch from remote if needed. +- Use `gh` to inspect PR review comments, PR issue comments, review threads if available, and check run summaries if relevant. +- Focus specifically on Greptile/review bot feedback and actionable reviewer comments. +- Pay particular attention to comments questioning whether a type contract is now wrong, whether a `// SAFETY:` comment is accurate, or whether a call site was missed. These are the likely real defects in this kind of PR. +- Address actionable comments with minimal follow-up fixes. +- Keep changes within the original selected files whenever possible. +- If a review comment requires changes outside the selected files, make only the minimal required supporting change. +- Do not perform unrelated cleanup. +- Do not rewrite the original PR. +- Do not force-push. +- Do not disable, downgrade, or ignore anti-slop rules, and do not add `any`, widen a type, or add an assertion to satisfy a reviewer comment. +- Follow the same fix standards as the original batch task, described in `.opencode/commands/as-fixes.md` under "What a good fix looks like" and "Hard prohibitions". Read that section before editing. Review pressure is exactly when a laundered fix is most tempting. + +After fixes, run: + +`bun run deslop -- check-batch --run ` + +Then re-run the package-scoped checks for the packages you touched, for example `bun run --cwd packages/ui type-check`, `bun run --cwd packages/ui lint`, and `bun run --cwd packages/ui test`. Workspace-wide checks are CI's job. + +Delivery: +- Commit follow-up fixes with a concise message. +- Push the branch. +- Reply to addressed review comments using `gh`. +- For each specific review comment you addressed, reply with what was changed and the follow-up commit hash. +- If the feedback was a general PR comment, add one general PR comment summarizing what was addressed, commit hashes, and validation results. +- Update the PR description so it stays true for the final HEAD: refresh `## Validation` with the checks you re-ran, and move any new behavior change into `## Risks and failure behavior`. Keep every heading of `.github/PULL_REQUEST_TEMPLATE.md` intact, and preserve content the repository owner added by hand, including screenshots. Read the live description before editing and merge into it rather than overwriting. +- If a comment is intentionally not addressed, reply with a concise reason. +- Do not release the batch while its PR is still open and awaiting review. The claim is what keeps parallel batches off these files. +- Release the batch only once its PR has been merged or closed: `bun run deslop -- release --run `. +- After the follow-up is complete, switch back to `main` and pull the latest remote changes. + +Constraints: +- Work on exactly one anti-slop batch PR. +- Prefer the oldest batch with an open PR. +- Do not auto-merge. +- Do not close the PR. +- Do not edit `CHANGELOG.md`, package versions, or release metadata. +- Do not release or delete handoff directories for batches you did not handle. +- If validation fails and cannot be fixed safely within scope, leave the batch claimed and report the blocker. diff --git a/.opencode/commands/maintenance-review.md b/.opencode/commands/maintenance-review.md new file mode 100644 index 00000000..d0ec290f --- /dev/null +++ b/.opencode/commands/maintenance-review.md @@ -0,0 +1,135 @@ +--- +description: Deeply review every open maintenance PR and fix it to completion, not by commenting +agent: build +--- + +You are working in the OpenChamber repository. + +Goal: take every open automated maintenance pull request and bring it to a state where a human reviewer would merge it without a single objection. You are the intelligence layer between unattended batch tasks and the repository owner. The batch tasks optimize for a metric; you optimize for the code being right. + +You do not leave review comments. You do the work. A finding you notice and do not fix is a failure of this task. + +## Scope of the run + +In scope: every open pull request whose head branch starts with `anti-slop/` or `react-doctor/`. + +Find them: + +`gh pr list --state open --search "head:anti-slop/" --json number,title,headRefName,url` + +`gh pr list --state open --search "head:react-doctor/" --json number,title,headRefName,url` + +Work through them one at a time, oldest first. Finish a PR completely before starting the next. Do not interleave. + +This task ends only when every PR in the list has been reviewed, fixed, validated, pushed, and its description updated. Do not stop at the first one. Do not stop because a PR looks acceptable at a glance; that judgement comes after reading the diff, not before. + +## Before you start + +Verify the worktree is clean: + +`git status --porcelain` + +If the output is not empty and the repository root contains a `.maintenance-clone` marker file, this is a disposable maintenance clone and the changes are debris from an earlier failed task. Recover it with `git checkout -- .`, `git clean -fd`, `git checkout main`, `git pull`, report exactly which files you discarded, and continue. + +If the marker file is absent, stop immediately and report it. Do not stash, reset, or discard anything. + +Read `AGENTS.md`, and read `.opencode/commands/as-fixes.md` in full, including the sections "What a good fix looks like" and "Hard prohibitions". Those describe the standard the anti-slop PRs were supposed to meet. Your job includes verifying they actually met it. + +Load every project skill matching the code you end up touching, exactly as `AGENTS.md` requires. These PRs reach into sync, stores, UI, runtime, and CLI code, and the applicable skill is determined by what you change, not by the fact that this is maintenance work. + +## Working on one PR + +Check out the branch and bring it up to date with `main`: + +`gh pr checkout ` + +`git merge origin/main` + +If the merge conflicts, resolve it correctly by reading both sides. Never resolve a conflict by taking one side wholesale to save time. + +Then read the entire diff against `main`, not just the changed lines: + +`git diff origin/main...HEAD` + +For every file in the diff, open the file itself and read the surrounding code. These PRs change type contracts and component structure, so a line that looks correct in isolation is frequently wrong in context. + +## What you are looking for + +Treat the PR body's claims as unverified. Re-run the checks yourself; do not trust reported results. + +Correctness of the change itself: +- Did the change alter runtime behavior? Effect cleanup, hook dependencies, component extraction, conditional object spreads, and added parsing all can. Decide whether the new behavior is right, not merely whether it is different. +- Does a removed or reordered object key change what gets serialized to an API, persisted to disk, or merged over defaults? A key that used to be absent and is now present as `undefined` is a real change. +- Was dead code removed that is actually referenced somewhere the batch task did not search, including dynamic imports, string-keyed lookups, generated assets, and other packages? +- Did a type contract change without every call site being updated? Search for each changed symbol across the workspace. +- Did an extracted component lose state, memoization, ref forwarding, or a stable identity that the original had? + +Honesty of the change: +- Is any `// SAFETY:` comment vague, generic, or untrue? A comment must name the check that already ran. If it does not, either delete the assertion by fixing the contract, or write the truthful comment. +- Was a type laundered rather than fixed? Look for invented primitive unions, `any`, new assertions, hand-written type predicates that merely relocate a rejected `typeof` check, or deleted fields and tests. +- Was a lint rule disabled, downgraded, ignored, or suppressed inline anywhere in the diff? Revert that and fix the underlying code. +- Was a new dependency, schema library, utility module, or architectural pattern introduced under the cover of cleanup? Remove it and solve the problem within existing precedent. + +Quality of the result: +- Does the new code read like the code around it, in naming, structure, and comment density? +- Are the new names accurate, or do they describe the refactor instead of the domain? +- Is the change complete, or did the batch task fix eight of eleven findings in a file and leave three arbitrary ones behind? + +## Fixing + +Fix everything you find, on the PR branch, as additional commits. You are explicitly permitted to go beyond the batch's original file scope when correctness requires it: update call sites, correct an upstream contract, add a missing test, or finish an incomplete refactor. + +Two boundaries on that freedom: + +1. Do not touch files that another open maintenance PR modifies. Check with `gh pr diff --name-only` for the other open PRs in this run. If a correct fix genuinely requires such a file, make the change in whichever PR already owns that file, and note the cross-PR dependency in both descriptions. +2. Do not turn a maintenance PR into a feature or a redesign. If you conclude the batch's approach was wrong at the root, revert that part of the diff rather than building on it, and explain the revert in the PR body. A smaller correct PR beats a larger clever one. + +Do not disable, downgrade, or ignore lint rules. Do not add `any`, widen a type, or add an assertion to make a check pass. Do not edit `oxlint.config.ts`, `tools/oxlint/anti-slop/`, `CHANGELOG.md`, package versions, or release metadata. + +If a batch left findings unfixed and the PR body called them skipped, evaluate each one yourself. Fix the ones that are fixable within a correct, reviewable change. Keep a skip only when you can articulate why fixing it would be wrong here, not merely hard. + +## Validating each PR + +Re-run the pipeline's own check for the batch, using the run id from the PR body when it is present: + +`bun run deslop -- check-batch --run ` for anti-slop PRs + +`bun run doctor -- check-batch --run ` for React Doctor PRs + +If the run directory no longer exists, skip that command and say so; it is a convenience, not the source of truth. + +Then, for every package the final diff touches, run its own checks: + +`bun run --cwd packages/ type-check` + +`bun run --cwd packages/ lint` + +`bun run --cwd packages/ test` + +Run `bunx oxlint ` on the files in the diff and confirm you have not increased anti-slop findings anywhere. + +For surfaces TypeScript does not cover, such as server JavaScript, CLI JavaScript, or Electron main-process helpers, run the focused tests for that surface. Static checks do not prove those correct. + +If a check fails for a reason unrelated to this PR, verify that claim by checking the same command on `main` before dismissing it, and report the result either way. + +## Delivering each PR + +- Commit your fixes with concise messages describing what was actually wrong. +- Push to the PR branch. Never force-push. +- Update the PR description so it describes the final state, using every heading of `.github/PULL_REQUEST_TEMPLATE.md` in the template's order. `## Intent` covers what the batch did and what you corrected; `## Non-goals` covers what you deliberately left alone; `## Affected surfaces` must reflect the final diff, including files you added beyond the batch scope; `## Repository guidance` must list the rules, skills, and module documentation that applied to your own edits, not only the batch's; `## Validation` must contain the exact commands you re-ran and their results; `## Risks and failure behavior` must carry every behavior change you accepted or introduced. A description that still describes only the batch's original work is incomplete. +- Preserve any content the repository owner added to the description by hand, including screenshots. Read the live description before editing it and merge your changes into it rather than overwriting. +- Add one PR comment summarizing your review pass, so the history shows what was examined and what was changed. +- Do not merge, do not close, do not approve, and do not request review. +- Do not release the batch claim. The batch stays claimed until its PR is merged or closed. + +Then move to the next PR. + +## Finishing the run + +When every PR has been handled, return to `main` and pull: + +`git checkout main && git pull` + +Report, per PR: number, title, what was wrong, what you fixed, what you deliberately left alone and why, validation results, and your assessment of whether it is now ready to merge. State plainly if any PR is not ready and what blocks it. + +If you found nothing wrong in a PR, say that explicitly and describe what you checked to reach that conclusion. That is a valid outcome, but only after real inspection. diff --git a/.opencode/commands/rd-fixes.md b/.opencode/commands/rd-fixes.md index 381711b7..df2d6bb8 100644 --- a/.opencode/commands/rd-fixes.md +++ b/.opencode/commands/rd-fixes.md @@ -7,12 +7,35 @@ You are working in the OpenChamber repository. Goal: reduce React Doctor diagnostics in a small, reviewable maintenance PR. -Start by running: +This task can run unattended on a schedule, so it must be safe to start at any moment and must stop cleanly when there is nothing to do. + +First, verify the worktree is safe to use: + +`git status --porcelain` + +If the output is not empty, decide which of two situations you are in. + +If the repository root contains a `.maintenance-clone` marker file, this working copy is a disposable clone dedicated to unattended maintenance. Nothing in it is human work in progress, so leftover changes are debris from an earlier task that failed to clean up after itself. Recover the clone rather than stopping: + +``` +git checkout -- . +git clean -fd +git checkout main +git pull +``` + +Report exactly which files you discarded, then continue with the task. A failed predecessor must not be able to jam the pipeline for every later run. + +If the marker file is absent, this is a working copy a person uses. Stop immediately and report that the worktree has uncommitted changes. Do not stash, reset, discard, commit, or switch branches. + +Then run: `bun run doctor -- next-batch --min-issues 75 --max-issues 120` Use the command output as the source of truth for this task scope. +If the output contains `NO BATCH AVAILABLE`, stop immediately and report the printed reason. Do not create a branch, do not create a pull request, and do not look for other work. Concurrency is already handled: the command excludes files claimed by other active batches and refuses to exceed the active-batch limit. + Workflow: - Before generating the batch, switch to `main` and pull the latest remote changes. - Read the `next-batch` output carefully. @@ -23,19 +46,42 @@ Workflow: - Fix as many diagnostics as practical in the selected files. Your default should be to fix selected diagnostics, not to skip them. - Prefer direct, behavior-preserving fixes: missing effect cleanup, mutable effect dependencies, accessibility issues with semantic fixes, local performance improvements, Tailwind shorthand replacements, component extraction when the boundary is clear, dead-code removal after verifying no references, and reducer or derived-state cleanup when the state relationship is local and clear. - Handle larger diagnostics deliberately instead of skipping them: for component splits, extract the smallest coherent subcomponent that reduces the diagnostic while preserving props/state flow; for dead code, verify references with search before deleting exports, types, or files; for state architecture issues, prefer the smallest local reducer or derived-state simplification that preserves behavior; for render-function extraction, extract only stable render helpers that do not depend on large implicit closure state, or pass explicit props; for behavior-sensitive diagnostics, read the surrounding code first and preserve existing runtime behavior. -- Skip a diagnostic only when the fix would require broad architectural changes, unclear behavior changes, or changes outside the selected batch scope. If skipped, mention it in the PR body. +- Finish each selected file. A file is finished when it has zero React Doctor diagnostics, or when every remaining diagnostic has an individual, specific reason to stay. A half-fixed file will be selected again later and cost a second pull request, a second review, and a second merge over the same code. +- Before considering a file done, re-run `bun run doctor -- file ` and read what is left. Leaving more than roughly a quarter of a file's diagnostics behind means you have not finished. +- A group of diagnostics sharing one root cause counts as one reason, and that root cause is usually worth fixing rather than deferring. +- Skip a diagnostic when the fix would require unclear behavior changes, when the change would be so large that the pull request stops being reviewable, or when the only way you can see to close it is a change you would not defend in review. An honest skip is always better than a forced fix. Ordinary difficulty, on its own, is still not a reason. If skipped, give the specific reason in the PR body under `## Non-goals`. +- If a whole selected file turns out to need a deliberate architectural change rather than a cleanup, abort per "Aborting cleanly" and report that the file was a poor batch selection. - Do not suppress React Doctor diagnostics unless there is a clear false positive. - If a listed diagnostic requires changes outside the selected files, make only the minimal required supporting change. Do not expand the cleanup scope. +## Aborting cleanly + +You may reach a point where the batch cannot be completed correctly: validation keeps failing, or the only remaining way to close the findings is a pattern this task forbids. Stopping there is the right decision. Stopping there and walking away from a modified working copy is not. + +Whatever edits exist in the working copy at that moment are your own, made minutes ago in this session. They are not human work in progress, and nothing is lost by removing them. Leaving them behind jams every scheduled run that follows, because those runs correctly refuse to operate on a dirty worktree. + +So when you abort, in this order: + +1. Revert every file you modified: `git checkout -- `, plus `git clean -fd` for files you created. Verify with `git status --porcelain` that the result is empty. +2. Release the claim so the files return to the pool: ``bun run doctor -- release --run ``. +3. Return to `main`. +4. Report what you attempted, precisely why you stopped, and confirm that both the worktree is clean and the claim is released. + +Never leave a partially fixed working copy as a message to the next run. If a file resists a correct fix, that belongs in your report, not on disk. + After edits, run: `bun run doctor -- check-batch --run ` -Then run: +Then validate the packages you actually touched, not the whole workspace. For each affected package run its own checks, for example: -`bun run type-check` +`bun run --cwd packages/ui type-check` -`bun run lint` +`bun run --cwd packages/ui lint` + +`bun run --cwd packages/ui test` + +Workspace-wide `bun run type-check` and `bun run lint` are CI's job. Run them locally only when a change crosses package boundaries or touches shared contracts. For files that TypeScript does not cover, such as server or CLI JavaScript, run the focused tests for that surface instead. Validation and delivery: - Confirm selected files have fewer diagnostics than before. @@ -45,15 +91,20 @@ Validation and delivery: - Create exactly one PR with `gh pr create` using the exact printed `PR title`. - After the PR is created, switch back to `main` and pull the latest remote changes again. -PR requirements: +PR requirements. The repository has a mandatory pull request template at `.github/PULL_REQUEST_TEMPLATE.md`, and `AGENTS.md` requires it to be completed with concrete evidence for the final PR HEAD. Read the template and `CONTRIBUTING.md` before writing the description. Use every template heading, in the template's order, and do not invent replacement headings. Fill each section as follows. + - Use the exact printed `PR title`. -- Include the `Run ID`, `Batch name`, and `Branch name`. -- Include selected files. -- Include diagnostics fixed according to `check-batch`. -- Include remaining diagnostics in selected files. -- Include validation results for `bun run type-check` and `bun run lint`. -- Include a `Manual testing recommendations` section with focused checks for the changed behavior. Base it on the selected files and actual edits, for example checking affected dropdowns, keyboard navigation, model/agent selection, settings controls, or mobile/desktop variants. -- Include any skipped diagnostics and why. +- `## Intent`: state that this is an unattended maintenance batch, name the `Run ID`, `Batch name`, and `Branch name`, and say what behavior changes. When nothing observable changes, say so explicitly rather than leaving it implied. +- `## Non-goals`: the diagnostics left unfixed in the selected files, diagnostics elsewhere in the repository, and any refactor you deliberately did not start. Give the reason for each, not just the count. +- `## Affected surfaces`: the packages, runtimes, user-visible states, and persisted or external contracts the diff reaches. Name every runtime the changed code runs in, and explain why an apparently applicable runtime is unaffected. +- `## Repository guidance`: fill the table. List the `AGENTS.md` rules you followed, every project skill that matched the change, required skill references you read, and the nearest `README.md` or `DOCUMENTATION.md` for the touched modules. For each row explain why it applies and how the change complies. Do not list filenames without explanation. +- `## Validation`: fill the table with the exact commands you ran and their results, including `check-batch` and every package-scoped type-check, lint, and test command, naming the packages. Record failures honestly, including pre-existing failures unrelated to this PR, and say which checks you did not run. Do not claim runtime behavior from type-check or lint alone. +- `## Visual evidence`: these PRs usually have no visible change, so explain concretely why the diff cannot affect rendered behavior. If anything user-visible did change, attach before/after evidence for the affected states. +- `## Risks and failure behavior`: cover what breaks if a change is wrong, how to roll it back, and any compatibility, data, performance, or cross-runtime concern. State "None identified" only with a concrete reason. + +Add a `## Manual testing recommendations` section after the template sections, with focused checks for the changed behavior. Base it on the selected files and actual edits, for example checking affected dropdowns, keyboard navigation, model or agent selection, settings controls, and mobile or desktop variants. + +Also state, inside `## Intent`, the selected files and how many diagnostics `check-batch` reports as fixed and remaining. Constraints: - Keep the PR small and reviewable. @@ -61,4 +112,6 @@ Constraints: - Do not modify unrelated files except minimal supporting changes required by selected-file fixes. - Do not run broad formatting. - Do not fix diagnostics outside the selected files. -- Leave `.tmp/react-doctor/runs//` intact after creating the PR. These files are the handoff for the review follow-up task. +- Do not edit `CHANGELOG.md`, package versions, or release metadata. This is internal maintenance with no user-facing change. +- Leave the batch's run directory intact after creating the PR. `next-batch` prints its location. That directory is both the handoff for the review follow-up task and the claim that stops another batch, including the anti-slop pipeline, from touching the same files. Deleting it early lets a parallel batch collide with this PR. Never delete it by hand; use `bun run doctor -- release --run `. +- If you stop before creating a PR for any reason, release the claim with `bun run doctor -- release --run ` so the files return to the pool. diff --git a/.opencode/commands/rd-follow-up.md b/.opencode/commands/rd-follow-up.md index b3ee888b..7bac4435 100644 --- a/.opencode/commands/rd-follow-up.md +++ b/.opencode/commands/rd-follow-up.md @@ -7,16 +7,40 @@ You are working in the OpenChamber repository. Goal: follow up on an existing React Doctor maintenance PR, address Greptile/review bot feedback, and clean up the local batch handoff files when done. -Inspect local React Doctor batch handoff files: +This task can run unattended on a schedule, so it must be safe to start at any moment and must stop cleanly when there is nothing to do. -`find .tmp/react-doctor/runs -maxdepth 2 -name batch.json -print 2>/dev/null || true` +First, verify the worktree is safe to use: + +`git status --porcelain` + +If the output is not empty, decide which of two situations you are in. + +If the repository root contains a `.maintenance-clone` marker file, this working copy is a disposable clone dedicated to unattended maintenance. Nothing in it is human work in progress, so leftover changes are debris from an earlier task that failed to clean up after itself. Recover the clone rather than stopping: + +``` +git checkout -- . +git clean -fd +git checkout main +git pull +``` + +Report exactly which files you discarded, then continue with the task. A failed predecessor must not be able to jam the pipeline for every later run. + +If the marker file is absent, this is a working copy a person uses. Stop immediately and report that the worktree has uncommitted changes. Do not stash, reset, discard, commit, or switch branches. + +List the active batches: + +`bun run doctor -- active` + +The listing may include batches owned by the anti-slop pipeline; those are shown as `[pipeline as]`. Never touch them. Workflow: -- Read the available `.tmp/react-doctor/runs/*/batch.json` files. -- Find the most recent batch that has `branchName`, `batchName`, and `prTitle`. -- Read its `Run ID`, `Batch name`, `Branch name`, `PR title`, and selected files. -- Use `gh` to find the open PR for that branch or title. -- If no open PR exists for the batch, stop and report that there is no PR to follow up. +- If there are no active batches, stop and report that there is nothing to follow up. +- Each active batch corresponds to one open PR. Read its `batch.json` for `runId`, `branchName`, `batchName`, `prTitle`, and selected files. +- Use `gh` to find the open PR for each batch branch. +- Work on the oldest batch that has an open PR with unaddressed feedback. If several qualify, handle exactly one and leave the rest. +- If a batch's PR was already merged or closed, do not treat it as follow-up work. Release its claim with `bun run doctor -- release --run ` so its files return to the pool, then continue looking. +- If no batch has an open PR with actionable feedback, stop and report that. - Switch to the batch branch using the exact `branchName`. - Pull or update the branch from remote if needed. - Use `gh` to inspect PR review comments, PR issue comments, review threads if available, and check run summaries if relevant. @@ -32,9 +56,7 @@ After fixes, run: `bun run doctor -- check-batch --run ` -`bun run type-check` - -`bun run lint` +Then re-run the package-scoped checks for the packages you touched, for example `bun run --cwd packages/ui type-check`, `bun run --cwd packages/ui lint`, and `bun run --cwd packages/ui test`. Workspace-wide checks are CI's job. Delivery: - Commit follow-up fixes with a concise message. @@ -42,15 +64,17 @@ Delivery: - Reply to addressed review comments using `gh`. - For each specific review comment you addressed, reply with what was changed and the follow-up commit hash. - If the feedback was a general PR comment, add one general PR comment summarizing what was addressed, commit hashes, and validation results. +- Update the PR description so it stays true for the final HEAD: refresh `## Validation` with the checks you re-ran, and move any new behavior change into `## Risks and failure behavior`. Keep every heading of `.github/PULL_REQUEST_TEMPLATE.md` intact, and preserve content the repository owner added by hand, including screenshots. Read the live description before editing and merge into it rather than overwriting. - If a comment is intentionally not addressed, reply with a concise reason. -- After successful push and replies, delete only the completed batch handoff directory: `.tmp/react-doctor/runs//`. +- Do not release the batch while its PR is still open and awaiting review. The claim is what keeps parallel batches off these files. +- Release the batch only once its PR has been merged or closed: `bun run doctor -- release --run `. - After the follow-up is complete, switch back to `main` and pull the latest remote changes. Constraints: - Work on exactly one React Doctor batch PR. -- Prefer the most recent batch with an open PR. +- Prefer the oldest batch with an open PR. - Do not auto-merge. - Do not close the PR. -- Do not delete handoff files until comments are addressed, validation passes, and follow-up commits are pushed. -- Do not delete unrelated `.tmp/react-doctor/runs/*` directories. -- If validation fails and cannot be fixed safely within scope, do not delete the handoff directory. +- Do not edit `CHANGELOG.md`, package versions, or release metadata. +- Do not release or delete handoff directories for batches you did not handle. +- If validation fails and cannot be fixed safely within scope, leave the batch claimed and report the blocker. diff --git a/AGENTS.md b/AGENTS.md index f19ac241..9d2a437d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,6 +79,10 @@ task-required reference named by those skills. Skills are canonical for their detailed workflows and checklists. Treating this table as optional advice is a process violation. +**Always load `.agents/skills/communication-style/SKILL.md` at the start of +every task, before any analysis, tool call, or response. Apply its guidance to +all messages and written output, not only to user-facing copy or documentation.** + | Trigger | Required skill | |---|---| | Source/dependency changes, exports or package contracts, build/generated assets, or module ownership | `openchamber-change-discipline` | @@ -123,6 +127,7 @@ Before adding guidance to a skill, identify its canonical owner. If another skil - Prefer focused tests and package-scoped type-check/lint for executable source changes. - Use workspace-wide checks for cross-workspace contracts, root tooling, dependencies, or shared generated assets. - Run `bun run dead-code` when source files are added/deleted/renamed or exports, types, entrypoints, or import shape change; inspect its report because it is non-blocking. +- Run `bunx oxlint ` on TypeScript/JavaScript files you created or substantially rewrote. This runs the vendored `anti-slop` plugin, which rejects low-evidence typing: unjustified type assertions, `unknown`/`object`/`Record` contracts, ad hoc `typeof` narrowing, and module mocking. Fix findings in code you authored. Pre-existing findings elsewhere are a known backlog: do not mass-fix them, and never silence a rule, weaken severity, or launder types to make the check pass. - Do not assume TypeScript/lint covers server JS, CLI JS, Electron helpers, or native behavior; run focused tests, syntax checks, builds, or runtime validation for the touched surface. - For docs-only or isolated config changes, run the narrowest relevant validation. - Report exactly what was and was not validated. Static checks alone do not prove runtime, relay, performance, or platform correctness. diff --git a/CHANGELOG.md b/CHANGELOG.md index 33df576f..65659752 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,40 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +- Chat: if OpenCode restarts while a response is still running, the chat now stops with an interrupted state and a notification to continue instead of hanging silently (thanks to @sum117). + +## [1.19.0] - 2026-08-19 + +- **Settings/Integrations:** a new Integrations settings page lists Claude Code, Command Code, and Cursor plugins with install, update, setup, and remove actions, plus Discord and Telegram Coming soon placeholders. +- **Project knowledge:** the Project notes panel is now Project knowledge, with notes, todos, plans and their search in a resizable sidebar. Notes are cards you expand by clicking anywhere on them, plans open and edit in the panel itself instead of a separate tab, and notes and plans can be pinned as context. +- **Files:** drag files onto the Files sidebar to upload them into the project or a specific folder; existing files require confirmation before replacement, and open previews refresh after an upload (thanks to @makeittech, @alanzchen). +- Settings: OpenChamber no longer replaces a full OpenCode config with an empty `$schema`-only stub when the file uses JSON5-style unquoted keys; Settings changes now fail instead of wiping plugins, MCP servers, and providers (thanks to @makeittech). +- Chat: an open conversation no longer keeps re-coloring the same code blocks in the background, so browsing files with a chat open stops pinning a CPU core and spinning up the fans (thanks to @makeittech). +- Stability/Proxy: the local server now reuses its connection to OpenCode instead of opening a new one for every API request. Under sustained traffic the old behavior could use up every outgoing network port on the machine, at which point nothing on the computer could open a new connection until the traffic stopped and the ports were released (thanks to @alohaninja). +- Usage/Claude: Claude plan limits now work when you are signed in through Claude Code, without also signing into Anthropic in OpenCode; the account is read from Claude Code's own login on macOS, Linux, and WSL. The page shows your session and weekly limits again, adds per-model weekly limits and extra usage spending, and names your plan. Limits are kept on screen instead of disappearing when Anthropic temporarily blocks refreshes. +- Usage/Command Code: Command Code plan limits now appear in the Usage page and work status panel. +- Git: the pull request panel now follows the branch's current open PR, and an open PR always wins over an older merged or closed one. After a PR is merged or closed the panel keeps showing it as the branch's last PR and offers creating the next one right below it (thanks to @makeittech). +- Git/Worktrees: creating a worktree from a pull request now falls back to GitHub's pull-request reference when the source fork was deleted or cannot be reached, instead of failing before creating the worktree (thanks to @makeittech). +- Chat: new chats no longer start against a deleted last worktree directory; they fall back to the active project instead of saving the first message and never starting. +- Chat: typing with Chinese, Japanese, or Korean input methods no longer interrupts composition or jumps the cursor to the end of the composer (thanks to @makeittech). +- Chat: opening a busy subagent in the context panel now shows its history instead of only the working-status line (thanks to @makeittech). +- Chat: saved chats in the context panel open again instead of staying blank. +- Chat: the context meter no longer climbs over 100% (330% readouts) after turns with many tool calls and no longer jumps when reopening an older session; it now shows what the window actually holds, everywhere the value appears — header, context sidebar, work status panel, mini chat, and mobile (thanks to @pocharlies). +- Chat/Attachments: extracted Office and OpenDocument content is now capped and presented more compactly, preventing large documents and their images from overwhelming the message context. +- Projects: project names now match the folder name exactly, so `.ssh` and `opencode-claude` are no longer shown as `.Ssh` and `Opencode Claude` in the sidebar, window title, settings and notifications; names you renamed yourself are kept. +- Files: files reached through a symlink inside the workspace now open correctly instead of being rejected as outside the workspace. +- Settings: the session retention action you pick is now saved instead of being dropped (thanks to @Gautam0507). +- Mobile: connecting through an ngrok address now bypasses ngrok's browser warning page instead of failing the server check. +- Mobile/iOS: text selection in the chat composer now uses native CodeMirror selection handles. +- Desktop: browser pages served from a self-signed loopback HTTPS address now load instead of being blocked by the certificate warning. +- Browser: typing a comment on a page no longer triggers app shortcuts. +- Skills Catalog: the source is now named ClawHub instead of "ClawdHub" (thanks to @makeittech). + +## [1.18.4] - 2026-08-14 + - **Chat:** new messages now remain at the end of the conversation instead of jumping before older messages after the message ID sequence rolls over; history loading, revert, and redo follow the same chronological order. - **Stability:** a single internal error no longer shuts down the local server, which made the instance unreachable until it was restarted; the error is logged and the server keeps running. +- Mobile: connecting to a server that has authentication disabled now survives closing and reopening the app — auto-reconnect and the return-to-app check no longer treat the missing password token as a lost connection and kick back to the connect screen. - Browser: restoring or opening a dev server preview while connected to an instance over a relay or other non-standard address no longer crashes the app; the preview reports the tunnel as unavailable instead. ## [1.18.3] - 2026-08-14 diff --git a/bun.lock b/bun.lock index 17212605..753e10c4 100644 --- a/bun.lock +++ b/bun.lock @@ -6,25 +6,25 @@ "name": "openchamber-monorepo", "dependencies": { "@base-ui/react": "^1.4.0", - "@codemirror/autocomplete": "^6.20.0", - "@codemirror/commands": "^6.10.1", + "@codemirror/autocomplete": "^6.20.3", + "@codemirror/commands": "^6.11.0", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-css": "^6.3.1", "@codemirror/lang-go": "^6.0.1", - "@codemirror/lang-html": "^6.4.11", - "@codemirror/lang-javascript": "^6.2.4", + "@codemirror/lang-html": "^6.4.12", + "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", - "@codemirror/lang-markdown": "^6.5.0", + "@codemirror/lang-markdown": "^6.5.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/lang-rust": "^6.0.2", "@codemirror/lang-sql": "^6.10.0", "@codemirror/lang-xml": "^6.1.0", - "@codemirror/lang-yaml": "^6.1.2", - "@codemirror/language": "6.12.2", - "@codemirror/lint": "^6.9.2", - "@codemirror/search": "^6.6.0", - "@codemirror/state": "^6.5.4", - "@codemirror/view": "6.39.13", + "@codemirror/lang-yaml": "^6.1.3", + "@codemirror/language": "6.12.4", + "@codemirror/lint": "^6.9.7", + "@codemirror/search": "^6.7.1", + "@codemirror/state": "^6.7.1", + "@codemirror/view": "6.43.9", "@heroui/scroll-shadow": "^2.3.18", "@heroui/system": "^2.4.23", "@heroui/theme": "^2.4.23", @@ -65,6 +65,7 @@ "devDependencies": { "@clack/prompts": "^1.1.0", "@eslint/js": "^9.33.0", + "@oxlint/plugins": "1.78.0", "@remixicon/react": "^4.7.0", "@tailwindcss/postcss": "^4.0.0", "@types/dom-speech-recognition": "^0.0.12", @@ -83,6 +84,7 @@ "globals": "^16.3.0", "node-addon-api": "7.1.1", "nodemon": "^3.1.7", + "oxlint": "1.78.0", "patch-package": "^8.0.0", "sharp": "^0.35.0", "tailwindcss": "^4.0.0", @@ -95,7 +97,7 @@ }, "packages/electron": { "name": "@openchamber/electron", - "version": "1.18.2", + "version": "1.19.0", "dependencies": { "@openchamber/web": "workspace:*", "electron-context-menu": "^4.1.2", @@ -132,7 +134,7 @@ }, "packages/ui": { "name": "@openchamber/ui", - "version": "1.18.2", + "version": "1.19.0", "dependencies": { "@aparajita/capacitor-secure-storage": "^8.0.0", "@base-ui/react": "^1.4.0", @@ -141,34 +143,34 @@ "@capacitor/keyboard": "^8.0.0", "@capacitor/push-notifications": "^8.1.1", "@capacitor/status-bar": "^8.0.0", - "@codemirror/autocomplete": "^6.20.0", - "@codemirror/commands": "^6.10.1", + "@codemirror/autocomplete": "^6.20.3", + "@codemirror/commands": "^6.11.0", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-css": "^6.3.1", "@codemirror/lang-go": "^6.0.1", - "@codemirror/lang-html": "^6.4.11", - "@codemirror/lang-javascript": "^6.2.4", + "@codemirror/lang-html": "^6.4.12", + "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", - "@codemirror/lang-markdown": "^6.5.0", + "@codemirror/lang-markdown": "^6.5.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/lang-rust": "^6.0.2", "@codemirror/lang-sql": "^6.10.0", "@codemirror/lang-xml": "^6.1.0", - "@codemirror/lang-yaml": "^6.1.2", - "@codemirror/language": "6.12.2", + "@codemirror/lang-yaml": "^6.1.3", + "@codemirror/language": "6.12.4", "@codemirror/language-data": "^6.5.2", - "@codemirror/legacy-modes": "^6.5.2", - "@codemirror/lint": "^6.9.2", - "@codemirror/search": "^6.6.0", - "@codemirror/state": "^6.5.4", - "@codemirror/view": "6.39.13", + "@codemirror/legacy-modes": "^6.5.3", + "@codemirror/lint": "^6.9.7", + "@codemirror/search": "^6.7.1", + "@codemirror/state": "^6.7.1", + "@codemirror/view": "6.43.9", "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", "@lezer/highlight": "^1.2.3", "@opencode-ai/sdk": "1.18.18", "@pierre/diffs": "1.3.0-beta.6", - "@replit/codemirror-vim": "^6.3.0", + "@replit/codemirror-vim": "^6.4.0", "@simplewebauthn/browser": "13.3.0", "@tanstack/react-virtual": "3.14.5", "@xenova/transformers": "^2.17.2", @@ -236,7 +238,7 @@ }, "packages/vscode": { "name": "openchamber", - "version": "1.18.2", + "version": "1.19.0", "dependencies": { "@openchamber/ui": "workspace:*", "@opencode-ai/sdk": "1.18.18", @@ -259,7 +261,7 @@ }, "packages/web": { "name": "@openchamber/web", - "version": "1.18.2", + "version": "1.19.0", "bin": { "openchamber": "./bin/cli.js", }, @@ -268,7 +270,6 @@ "@octokit/rest": "^22.0.1", "@opencode-ai/sdk": "1.18.18", "@simplewebauthn/server": "13.3.1", - "adm-zip": "^0.6.0", "bun-pty": "^0.4.5", "compression": "^1.8.1", "cron-parser": "^4.9.0", @@ -304,7 +305,6 @@ "@remixicon/react": "^4.7.0", "@simplewebauthn/browser": "13.3.0", "@tailwindcss/postcss": "^4.0.0", - "@types/adm-zip": "^0.5.7", "@types/node": "^24.3.1", "@types/react": "^19.1.10", "@types/react-dom": "^19.1.7", @@ -353,8 +353,18 @@ "bun-pty@0.4.8": "bun-patches/bun-pty@0.4.8.patch", }, "overrides": { - "@codemirror/language": "6.12.2", - "@codemirror/view": "6.39.13", + "@codemirror/autocomplete": "6.20.3", + "@codemirror/commands": "6.11.0", + "@codemirror/lang-html": "6.4.12", + "@codemirror/lang-javascript": "6.2.5", + "@codemirror/lang-markdown": "6.5.2", + "@codemirror/lang-yaml": "6.1.3", + "@codemirror/language": "6.12.4", + "@codemirror/legacy-modes": "6.5.3", + "@codemirror/lint": "6.9.7", + "@codemirror/search": "6.7.1", + "@codemirror/state": "6.7.1", + "@codemirror/view": "6.43.9", }, "packages": { "7zip-bin": ["7zip-bin@5.2.0", "", {}, "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A=="], @@ -601,9 +611,9 @@ "@clack/prompts": ["@clack/prompts@1.1.0", "", { "dependencies": { "@clack/core": "1.1.0", "sisteransi": "^1.0.5" } }, "sha512-pkqbPGtohJAvm4Dphs2M8xE29ggupihHdy1x84HNojZuMtFsHiUlRvqD24tM2+XmI+61LlfNceM3Wr7U5QES5g=="], - "@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.0", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-bOwvTOIJcG5FVo5gUUupiwYh8MioPLQ4UcqbcRf7UQ98X90tCa9E1kZ3Z7tqwpZxYyOvh1YTYbmZE9RTfTp5hg=="], + "@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.3", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g=="], - "@codemirror/commands": ["@codemirror/commands@6.10.2", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-vvX1fsih9HledO1c9zdotZYUZnE4xV0m6i3m25s5DIfXofuprk6cRcLUZvSk3CASUbwjQX21tOGbkY2BH8TpnQ=="], + "@codemirror/commands": ["@codemirror/commands@6.11.0", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-/K4Rl5BN0OtTiPWmJCdqODu38XnDMsDxKY5rgrPnCkutPTJf2wVbkoixLfealF5Kwse/s8P8M5jAiURiwSwnFA=="], "@codemirror/lang-angular": ["@codemirror/lang-angular@0.1.4", "", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.3" } }, "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g=="], @@ -613,11 +623,11 @@ "@codemirror/lang-go": ["@codemirror/lang-go@6.0.1", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/go": "^1.0.0" } }, "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg=="], - "@codemirror/lang-html": ["@codemirror/lang-html@6.4.11", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw=="], + "@codemirror/lang-html": ["@codemirror/lang-html@6.4.12", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w=="], "@codemirror/lang-java": ["@codemirror/lang-java@6.0.2", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/java": "^1.0.0" } }, "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ=="], - "@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.4", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-0WVmhp1QOqZ4Rt6GlVGwKJN3KW7Xh4H2q8ZZNGZaP6lRdxXJzmjm4FqvmOojVj6khWJHIb9sp7U/72W7xQgqAA=="], + "@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.5", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A=="], "@codemirror/lang-jinja": ["@codemirror/lang-jinja@6.0.0", "", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.4.0" } }, "sha512-47MFmRcR8UAxd8DReVgj7WJN1WSAMT7OJnewwugZM4XiHWkOjgJQqvEM1NpMj9ALMPyxmlziEI1opH9IaEvmaw=="], @@ -627,7 +637,7 @@ "@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw=="], - "@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.0", "", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-0K40bZ35jpHya6FriukbgaleaqzBLZfOh7HuzqbMxBXkbYMJDxfF39c23xOgxFezR+3G+tR2/Mup+Xk865OMvw=="], + "@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="], "@codemirror/lang-php": ["@codemirror/lang-php@6.0.2", "", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/php": "^1.0.0" } }, "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA=="], @@ -645,21 +655,21 @@ "@codemirror/lang-xml": ["@codemirror/lang-xml@6.1.0", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/xml": "^1.0.0" } }, "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg=="], - "@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-dxrfG8w5Ce/QbT7YID7mWZFKhdhsaTNOYjOkSIMt1qmC4VQnXSDSYVHHHn8k6kJUfIhtLo8t1JJgltlxWdsITw=="], + "@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.3", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ=="], - "@codemirror/language": ["@codemirror/language@6.12.2", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-jEPmz2nGGDxhRTg3lTpzmIyGKxz3Gp3SJES4b0nAuE5SWQoKdT5GoQ69cwMmFd+wvFUhYirtDTr0/DRHpQAyWg=="], + "@codemirror/language": ["@codemirror/language@6.12.4", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A=="], "@codemirror/language-data": ["@codemirror/language-data@6.5.2", "", { "dependencies": { "@codemirror/lang-angular": "^0.1.0", "@codemirror/lang-cpp": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-go": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-java": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/lang-jinja": "^6.0.0", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-less": "^6.0.0", "@codemirror/lang-liquid": "^6.0.0", "@codemirror/lang-markdown": "^6.0.0", "@codemirror/lang-php": "^6.0.0", "@codemirror/lang-python": "^6.0.0", "@codemirror/lang-rust": "^6.0.0", "@codemirror/lang-sass": "^6.0.0", "@codemirror/lang-sql": "^6.0.0", "@codemirror/lang-vue": "^0.1.1", "@codemirror/lang-wast": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.4.0" } }, "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg=="], - "@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.2", "", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/jJbwSTazlQEDOQw2FJ8LEEKVS72pU0lx6oM54kGpL8t/NJ2Jda3CZ4pcltiKTdqYSRk3ug1B3pil1gsjA6+8Q=="], + "@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.3", "", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg=="], - "@codemirror/lint": ["@codemirror/lint@6.9.4", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.35.0", "crelt": "^1.0.5" } }, "sha512-ABc9vJ8DEmvOWuH26P3i8FpMWPQkduD9Rvba5iwb6O3hxASgclm3T3krGo8NASXkHCidz6b++LWlzWIUfEPSWw=="], + "@codemirror/lint": ["@codemirror/lint@6.9.7", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="], - "@codemirror/search": ["@codemirror/search@6.6.0", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-koFuNXcDvyyotWcgOnZGmY7LZqEOXZaaxD/j6n18TCLx2/9HieZJ5H6hs1g8FiRxBD0DNfs0nXn17g872RmYdw=="], + "@codemirror/search": ["@codemirror/search@6.7.1", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA=="], - "@codemirror/state": ["@codemirror/state@6.5.4", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-8y7xqG/hpB53l25CIoit9/ngxdfoG+fx+V3SHBrinnhOtLvKHRyAJJuHzkWrR4YXXLX8eXBsejgAAxHUOdW1yw=="], + "@codemirror/state": ["@codemirror/state@6.7.1", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-9QzNDgE4EYDnAHfrTlR2lwiPciiOymLtwKK+8yHQzCc7GXhAP9xdEbEJFy2IWB1j9UGUl9BsgMmTo/ImA02T7A=="], - "@codemirror/view": ["@codemirror/view@6.39.13", "", { "dependencies": { "@codemirror/state": "^6.5.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-QBO8ZsgJLCbI28KdY0/oDy5NQLqOQVZCozBknxc2/7L98V+TVYFHnfaCsnGh1U+alpd2LOkStVwYY7nW2R1xbw=="], + "@codemirror/view": ["@codemirror/view@6.43.9", "", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-sTuUzTpPMFebRhg6dawChoKKgndIwfjmJgKVxBefPElcU2NwQ6AFroupk0SFqEerQyZOGRfDNnSN8Dw/lMAsXw=="], "@date-fns/tz": ["@date-fns/tz@1.4.1", "", {}, "sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA=="], @@ -995,6 +1005,46 @@ "@opencode-ai/sdk": ["@opencode-ai/sdk@1.18.18", "", { "dependencies": { "cross-spawn": "7.0.6" } }, "sha512-zJlwXskIR47V1dkPJqeKBgq7nejG1uU8lJaGIGqbX3MWRCT8vKn0fEotbxuPCKnTdmWsDyNGNg9q1qIliDSMDA=="], + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.78.0", "", { "os": "android", "cpu": "arm" }, "sha512-Bu819lmAfZMUHErrpe0cEWj3iaefuUODHSU8+UbXy67V/r7/7f4K3FL0NmbD85E+wiFLDYuhP8Zlv0XnVeXshw=="], + + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.78.0", "", { "os": "android", "cpu": "arm64" }, "sha512-CDfxZgB61B7buRdY2FJoAYYPPXCZ1EoC1LKscnC5dg3kjobdxiconvAvvN1BmHyW4PyFT3jRLDag/BY/roSNBQ=="], + + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.78.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2Y2U9Ahrz+OO0Ej88f9SJYq51/jUBp1Mc7iZu0ukrbeeZ3gpRGfzIFnoqfHDY96xr0GEfNrPUBFEy0nN5aD7HA=="], + + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.78.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-rpych6eJq6m9jDRypTEaPD1xysaEW5h9+xuxhGK/QhOg+/xaqPZrCrTNoIl/f3nEjuJeCEmstNDlrE9rJi/3/g=="], + + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.78.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-IcMGrQT3QizkOESUJd5et+rOhVqSkNDfNik1cvrKDqIbzqx9KMtRswpFgkCuNTSwylCFLKhGUu8KmqY1ZnC0Dg=="], + + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.78.0", "", { "os": "linux", "cpu": "arm" }, "sha512-/uLdoJ0IXE6vo/0f0LKjinQAp+re+VMaCWaNT8ENIv2EOCkSsc8SGaflXAuW0Jua2dq5+GLVWm1NQK7P3UFSNQ=="], + + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.78.0", "", { "os": "linux", "cpu": "arm" }, "sha512-7xi4Wb/O8NRJhLoUXmDJMUVpNYvB5kefdhFU1Jb8rtae4QoXlTiLwI14X4YvAXVZLNZChP8m5qO9SQAlWQTbkQ=="], + + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.78.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-4hFW0+fVXa3OIh1Y4A5SPkmvI4wuuBSrCVKzOyE7PTjhc7yEqZ1pmvEEeS5Lj/MaqvegFxXyF33N+6jkehxdyg=="], + + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.78.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-oC0mvsgBJjlMijSDEhx9KuvR9zYeHXceA9MjbuXB1F8NSR78Yj2unOBrstEvTVaq+pko+kuue6DajC00eqvTdg=="], + + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.78.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-XAllT5SUZS+ohjuZ3/5S0cwe0r7eboiuigeStCZ5DXRYx/2KVM2UvQXvAfyzXEimtQjAB7cDQ2YxDe2Zl2WNQQ=="], + + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.78.0", "", { "os": "linux", "cpu": "none" }, "sha512-trucMER/0QtecoXvc1y/UVqE3kwJipDwrx4oHfj+nNm3dq2zjP44WT0CfHNDPM3G1DXIkx/gY6lAD21NSCZVhA=="], + + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.78.0", "", { "os": "linux", "cpu": "none" }, "sha512-cm3O4F/HQbdzOUX5mKHqG5KDL6E5w0pnlZ+fbBy2rmLryPOowkuLagFHTopQsEIpjcaZoPOrL+BmmAytAG9HFg=="], + + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.78.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-33wRf6HqGNsybJ3qX4cGaQN2ODPxNmc1rMa0mrTmx3eFq1VzOnvQooi9bIGVYakW8a/wmqVx1mgsUm8R2xfTiw=="], + + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.78.0", "", { "os": "linux", "cpu": "x64" }, "sha512-rRdISSYegj6VganMZ9tjRjijowfHJ09IZU01i0toBAqr6n5LEtwHq2IeS4FjW2RoskOHlb6efB26H5izYb3GEQ=="], + + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.78.0", "", { "os": "linux", "cpu": "x64" }, "sha512-GmsP4rW0xTL6u5CVdcDsaN5Fbc7hBc382Wmar1kttbnwSEviM+rSINKOMQ+UQ6iH+AGwC+8gaAiwu134Tgh6Lg=="], + + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.78.0", "", { "os": "none", "cpu": "arm64" }, "sha512-sy9yeYuADc8a+n4TLBayzMCZiHPW78DcIFVpOXTmdKHWQeM9xe5uzkqIIZmi326D5hY9XVwacipEB1p7tQjPAg=="], + + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.78.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-rjc2hF1KfMi8fZj1X/m3AmnHbdsF3rL0v6KQg0Uc880Yb2khjz+3U14sfdZ7jWTpRnN1m1NQa/TT7uU9lJWPrA=="], + + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.78.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-zcuXFVrEFHIafRfkCQT8w/Xe41o07ozl/vwHq7p94vB29xVzsB0sZGYORU1jhcYKv3Lr0J3HbJ2T4fHH5rWmvA=="], + + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.78.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Sb5ocmLSuYeOuXd+CFOToGKp/gjXUEWDnvIGwhnh8aq8wY4TMmEnKnvbogSW7RdMZv77JSARduS7/gv+khYEjA=="], + + "@oxlint/plugins": ["@oxlint/plugins@1.78.0", "", {}, "sha512-Ypt8KeRYw+4jUtlPirfcHWMrn5ms12VrrFPD+Mds477/7tJxG1Kcz2Yrg2nVcTQEUx/GdlhS+BUg1kmxNm04Ug=="], + "@paralleldrive/cuid2": ["@paralleldrive/cuid2@2.3.1", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="], "@peculiar/asn1-android": ["@peculiar/asn1-android@2.6.0", "", { "dependencies": { "@peculiar/asn1-schema": "^2.6.0", "asn1js": "^3.0.6", "tslib": "^2.8.1" } }, "sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ=="], @@ -1149,7 +1199,9 @@ "@remixicon/react": ["@remixicon/react@4.9.0", "", { "peerDependencies": { "react": ">=18.2.0" } }, "sha512-5/jLDD4DtKxH2B4QVXTobvV1C2uL8ab9D5yAYNtFt+w80O0Ys1xFOrspqROL3fjrZi+7ElFUWE37hBfaAl6U+Q=="], - "@replit/codemirror-vim": ["@replit/codemirror-vim@6.3.0", "", { "peerDependencies": { "@codemirror/commands": "6.x.x", "@codemirror/language": "6.x.x", "@codemirror/search": "6.x.x", "@codemirror/state": "6.x.x", "@codemirror/view": "6.x.x" } }, "sha512-aTx931ULAMuJx6xLf7KQDOL7CxD+Sa05FktTDrtLaSy53uj01ll3Zf17JdKsriER248oS55GBzg0CfCTjEneAQ=="], + "@replit/codemirror-vim": ["@replit/codemirror-vim@6.4.0", "", { "dependencies": { "@replit/codemirror-vim-core": "^0.1.0" }, "peerDependencies": { "@codemirror/commands": "6.x.x", "@codemirror/language": "6.x.x", "@codemirror/search": "6.x.x", "@codemirror/state": "6.x.x", "@codemirror/view": "6.x.x" } }, "sha512-t9UMDNhkmeAkl0uRbiJVotv97bGD6mf4GyJJoEbrjUqa/Pov0s9eL+4AaI0Xto3OGri17i9qwIpT0JbVlVXt8A=="], + + "@replit/codemirror-vim-core": ["@replit/codemirror-vim-core@0.1.0", "", {}, "sha512-1i6EBKpcNfDKvTmTh6N6g9lL6udD5t+uFNh4JCqozRnVlvUGOps7h/QzS2ne4zcvPUjvApKpmcP7Grc3fNbZiQ=="], "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="], @@ -2663,6 +2715,8 @@ "own-keys": ["own-keys@1.0.1", "", { "dependencies": { "get-intrinsic": "^1.2.6", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg=="], + "oxlint": ["oxlint@1.78.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.78.0", "@oxlint/binding-android-arm64": "1.78.0", "@oxlint/binding-darwin-arm64": "1.78.0", "@oxlint/binding-darwin-x64": "1.78.0", "@oxlint/binding-freebsd-x64": "1.78.0", "@oxlint/binding-linux-arm-gnueabihf": "1.78.0", "@oxlint/binding-linux-arm-musleabihf": "1.78.0", "@oxlint/binding-linux-arm64-gnu": "1.78.0", "@oxlint/binding-linux-arm64-musl": "1.78.0", "@oxlint/binding-linux-ppc64-gnu": "1.78.0", "@oxlint/binding-linux-riscv64-gnu": "1.78.0", "@oxlint/binding-linux-riscv64-musl": "1.78.0", "@oxlint/binding-linux-s390x-gnu": "1.78.0", "@oxlint/binding-linux-x64-gnu": "1.78.0", "@oxlint/binding-linux-x64-musl": "1.78.0", "@oxlint/binding-openharmony-arm64": "1.78.0", "@oxlint/binding-win32-arm64-msvc": "1.78.0", "@oxlint/binding-win32-ia32-msvc": "1.78.0", "@oxlint/binding-win32-x64-msvc": "1.78.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2001", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-QgQePuxIqKOzo1KSjG2EnITEeWvWnKAm77eq8nrMtf6AGoA+zyGc4PFYtDNJSD25g/ibOwfQ851hZ4/SPkMVoA=="], + "p-cancelable": ["p-cancelable@2.1.1", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="], "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], diff --git a/oxlint.config.ts b/oxlint.config.ts new file mode 100644 index 00000000..00409e7d --- /dev/null +++ b/oxlint.config.ts @@ -0,0 +1,47 @@ +import { defineConfig } from "oxlint"; + +// Oxlint here runs only the vendored anti-slop plugin; ESLint remains the +// general-purpose linter for this repository. +export default defineConfig({ + categories: { + correctness: "off", + }, + ignorePatterns: [ + "**/node_modules/**", + "**/dist/**", + "**/build/**", + "**/out/**", + "**/.next/**", + "**/ios/**", + "**/android/**", + ".agents/**", + ".claude/**", + ".conductor/**", + ".opencode/**", + ".openchamber/**", + ".tmp/**", + "patches/**", + "bun-patches/**", + "tools/oxlint/anti-slop/**", + ], + jsPlugins: [ + { name: "anti-slop", specifier: "./tools/oxlint/anti-slop/index.ts" }, + ], + rules: { + "anti-slop/no-chained-type-assertions": "error", + "anti-slop/no-conditional-empty-object-spread": "error", + "anti-slop/no-known-value-widening": "error", + "anti-slop/no-module-mocking": "error", + "anti-slop/no-object-parameters": "error", + "anti-slop/no-reflect-apply": "error", + "anti-slop/no-reflect-get": "error", + "anti-slop/no-runtime-typeof": "error", + "anti-slop/no-shape-in-symbol-names": "error", + "anti-slop/no-unknown-parameters": "error", + "anti-slop/no-unknown-returns": "error", + "anti-slop/no-unknown-type-aliases": "error", + "anti-slop/no-unsafe-dictionary-type": "error", + "anti-slop/no-widen-then-assert": "error", + "anti-slop/require-safety-comment-for-type-assertion": "error", + }, +}); diff --git a/package.json b/package.json index 077f8a83..704434b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openchamber-monorepo", - "version": "1.18.3", + "version": "1.19.0", "description": "OpenChamber monorepo workspace for web, ui, and desktop runtimes", "private": true, "type": "module", @@ -38,6 +38,7 @@ "lint:ui": "bun run --cwd packages/ui lint", "lint:electron": "bun run --cwd packages/electron lint", "lint:mobile": "bun run --cwd packages/mobile lint", + "lint:anti-slop": "oxlint", "test": "node scripts/run-isolated-tests.mjs scripts && bun run --cwd packages/ui test && bun run --cwd packages/vscode test && bun run --cwd packages/electron test && bun run --cwd packages/web test", "clean": "bun run --filter '*' clean", "changelog-card": "node scripts/changelog-card/generate.mjs", @@ -74,6 +75,7 @@ "docs:validate": "node scripts/docs/validate-docs.mjs", "dead-code": "bunx knip@5.80.0 --no-exit-code --include files,exports,nsExports,types,nsTypes,enumMembers,duplicates", "doctor": "node scripts/react-doctor.mjs", + "deslop": "node scripts/anti-slop.mjs", "profile:browser": "node scripts/profile-browser.mjs", "icons:sprite": "node scripts/generate-file-type-sprite.mjs", "icons:generate": "bun run scripts/generate-icon-sprite.mjs", @@ -89,25 +91,25 @@ }, "dependencies": { "@base-ui/react": "^1.4.0", - "@codemirror/autocomplete": "^6.20.0", - "@codemirror/commands": "^6.10.1", + "@codemirror/autocomplete": "^6.20.3", + "@codemirror/commands": "^6.11.0", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-css": "^6.3.1", "@codemirror/lang-go": "^6.0.1", - "@codemirror/lang-html": "^6.4.11", - "@codemirror/lang-javascript": "^6.2.4", + "@codemirror/lang-html": "^6.4.12", + "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", - "@codemirror/lang-markdown": "^6.5.0", + "@codemirror/lang-markdown": "^6.5.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/lang-rust": "^6.0.2", "@codemirror/lang-sql": "^6.10.0", "@codemirror/lang-xml": "^6.1.0", - "@codemirror/lang-yaml": "^6.1.2", - "@codemirror/language": "6.12.2", - "@codemirror/lint": "^6.9.2", - "@codemirror/search": "^6.6.0", - "@codemirror/state": "^6.5.4", - "@codemirror/view": "6.39.13", + "@codemirror/lang-yaml": "^6.1.3", + "@codemirror/language": "6.12.4", + "@codemirror/lint": "^6.9.7", + "@codemirror/search": "^6.7.1", + "@codemirror/state": "^6.7.1", + "@codemirror/view": "6.43.9", "@heroui/scroll-shadow": "^2.3.18", "@heroui/system": "^2.4.23", "@heroui/theme": "^2.4.23", @@ -146,12 +148,24 @@ "zustand": "^5.0.8" }, "overrides": { - "@codemirror/language": "6.12.2", - "@codemirror/view": "6.39.13" + "@codemirror/autocomplete": "6.20.3", + "@codemirror/commands": "6.11.0", + "@codemirror/lang-html": "6.4.12", + "@codemirror/lang-javascript": "6.2.5", + "@codemirror/lang-markdown": "6.5.2", + "@codemirror/lang-yaml": "6.1.3", + "@codemirror/language": "6.12.4", + "@codemirror/legacy-modes": "6.5.3", + "@codemirror/lint": "6.9.7", + "@codemirror/search": "6.7.1", + "@codemirror/state": "6.7.1", + "@codemirror/view": "6.43.9" }, "devDependencies": { "@clack/prompts": "^1.1.0", "@eslint/js": "^9.33.0", + "@oxlint/plugins": "1.78.0", + "@remixicon/react": "^4.7.0", "@tailwindcss/postcss": "^4.0.0", "@types/dom-speech-recognition": "^0.0.12", "@types/node": "^24.3.1", @@ -169,8 +183,8 @@ "globals": "^16.3.0", "node-addon-api": "7.1.1", "nodemon": "^3.1.7", + "oxlint": "1.78.0", "patch-package": "^8.0.0", - "@remixicon/react": "^4.7.0", "sharp": "^0.35.0", "tailwindcss": "^4.0.0", "tsx": "^4.20.6", diff --git a/packages/docs/content/docs/de/integrations.mdx b/packages/docs/content/docs/de/integrations.mdx new file mode 100644 index 00000000..42f5972b --- /dev/null +++ b/packages/docs/content/docs/de/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Integrationen +description: Nutze dein Claude-, Command-Code- oder Cursor-Abo als Provider. +--- + +# Integrationen + +Eine Integration ist ein kleines Plugin, das OpenChamber einen Provider hinzufügt — auf Basis eines Abos, das du bereits hast. Verwalten kannst du sie unter **Settings → Integrations**. + +Verfügbare Integrationen: + +- **Claude Code** — dein Claude Pro- oder Max-Plan, ohne API-Keys +- **Command Code** — dein Command-Code-Plan +- **Cursor** — die Modell-Limits deines Cursor-Plans + +## Integration installieren + +1. Öffne **Settings → Integrations**. +2. Suche die Integration und wähle **Install**. +3. Starte OpenCode neu, wenn darum gebeten wird — der Provider erscheint nach dem Neustart. +4. Wähle **Set up** und melde dich an. Die Modelle erscheinen danach in der Modellauswahl im Chat. + +Integrationen werden für deinen Benutzer installiert und funktionieren damit in jedem Projekt. Aktualisieren oder entfernen kannst du sie jederzeit über dieselbe Karte. + +## Claude Code + +Claude Code nutzt deinen Claude Pro- oder Max-Plan — ohne API-Keys und ohne separate Claude-App. + +1. Installiere die Integration (siehe oben). +2. Wähle **Set up** und melde dich an. Wenn du die Claude Code CLI noch nicht hast, bietet die Einrichtung an, sie zuerst zu installieren, und meldet dich danach an. + +Claude Code ist die einzige Integration hier, die ihre Provider-CLI installiert und angemeldet benötigt. Command Code und Cursor brauchen ihre CLIs nicht. + +**Wie dein Claude-Konto geschützt bleibt:** Diese Integration nutzt das offizielle Claude Agent SDK von Anthropic und deine installierte Claude Code CLI. Sie kapert kein OAuth, extrahiert oder wiederholt keine Browser-Tokens, gibt sich nicht als nicht unterstützter Client aus und umgeht nicht Anthropics Authentifizierung. Sie bleibt auf dem von Anthropic unterstützten Zugriffsweg und trägt daher nicht das mit Token-Hijacking oder unautorisierten Authentifizierungsumgehungen verbundene Sperrrisiko. + +## Command Code + +Command Code nutzt deinen Command-Code-Plan. + +1. Installiere die Integration (siehe oben). +2. Wähle **Set up** — es öffnet sich eine Browserseite. Genehmige den Zugriff und kehre zu OpenChamber zurück. + +Auf einem Headless-Server oder in CI setze stattdessen die Umgebungsvariable `COMMAND_CODE_API_KEY`, anstatt dich im Browser anzumelden. + +## Cursor + +Cursor macht die Modelle deines Cursor-Plans in OpenChamber nutzbar. + +1. Installiere die Integration (siehe oben). +2. Wähle **Set up**, öffne den Link und genehmige den Zugriff im Browser. Kein API-Key nötig. Die Modellliste lädt nach der Anmeldung automatisch. + +## Aktualisieren oder entfernen + +- **Update** installiert die neueste veröffentlichte Version des Plugins. +- **Remove** löscht das Plugin aus deiner OpenCode-Konfiguration. Der Provider wird beim nächsten Neuladen von OpenCode nicht mehr geladen. + +Wenn eine Karte meldet, dass Einträge manuell verwaltet werden müssen, wähle **Manage plugins** und bereinige die Duplikate dort. + +## Verwandtes + +- [Anbieter, Modelle und Agenten](/de/providers/) — weitere Provider verbinden und Modelle wählen +- [Nutzung und Kontingente](/de/usage/) — verfolge, wie viel du genutzt hast diff --git a/packages/docs/content/docs/de/providers.mdx b/packages/docs/content/docs/de/providers.mdx index 4d5738f5..f559dab2 100644 --- a/packages/docs/content/docs/de/providers.mdx +++ b/packages/docs/content/docs/de/providers.mdx @@ -45,5 +45,6 @@ Provider-Anmeldungen werden von OpenCode gespeichert, nicht von OpenChamber, dah ## Weiterführend +- [Integrationen](/integrations/) — nutze ein Claude-, Command-Code- oder Cursor-Abo als Provider - [MCP-Server](/mcp/) — füge Agents zusätzliche Werkzeuge hinzu - [Nutzung & Kontingente](/usage/) — verfolge, wie viel du verbraucht hast diff --git a/packages/docs/content/docs/de/skills-catalog.mdx b/packages/docs/content/docs/de/skills-catalog.mdx index 1b1c35a7..7026837b 100644 --- a/packages/docs/content/docs/de/skills-catalog.mdx +++ b/packages/docs/content/docs/de/skills-catalog.mdx @@ -12,7 +12,7 @@ Zum Schreiben eigener Skills siehe [Skills](/skills/). ## Einen Skill installieren 1. Öffne den Katalog. -2. Durchsuche die eingebauten Quellen — das Anthropic-Skills-Repo und die ClawdHub-Community-Registry — oder nutze die Suche. +2. Durchsuche die eingebauten Quellen — wie das Anthropic-Skills-Repo — oder nutze die Suche. 3. Wähle einen Skill aus und installiere ihn. 4. Entscheide, wo er installiert werden soll: für alles, was du tust, oder nur für das aktuelle Projekt. diff --git a/packages/docs/content/docs/es/integrations.mdx b/packages/docs/content/docs/es/integrations.mdx new file mode 100644 index 00000000..206e40d8 --- /dev/null +++ b/packages/docs/content/docs/es/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Integraciones +description: Usa tu suscripción de Claude, Command Code o Cursor como proveedor. +--- + +# Integraciones + +Una integración es un pequeño plugin que añade un proveedor a OpenChamber usando una suscripción que ya tienes. Las gestionas en **Settings → Integrations**. + +Integraciones disponibles: + +- **Claude Code** — tu plan Claude Pro o Max, sin claves de API +- **Command Code** — tu plan de Command Code +- **Cursor** — los límites de modelos de tu plan de Cursor + +## Instalar una integración + +1. Abre **Settings → Integrations**. +2. Busca la integración y elige **Install**. +3. Reinicia OpenCode cuando se te pida — el proveedor aparece tras el reinicio. +4. Elige **Set up** e inicia sesión. Los modelos aparecerán luego en el selector de modelos del chat. + +Las integraciones se instalan para tu usuario, así que funcionan en todos los proyectos. Puedes actualizarlas o eliminarlas desde la misma tarjeta en cualquier momento. + +## Claude Code + +Claude Code usa tu plan Claude Pro o Max — sin claves de API y sin una app de Claude aparte. + +1. Instala la integración (arriba). +2. Elige **Set up** e inicia sesión. Si aún no tienes la CLI de Claude Code, la configuración ofrece instalarla primero y luego iniciar sesión. + +Claude Code es la única integración de esta página que requiere tener la CLI de su proveedor instalada y con sesión iniciada. Command Code y Cursor no requieren sus CLIs. + +**Cómo se protege tu cuenta de Claude:** esta integración usa el Claude Agent SDK oficial de Anthropic y tu CLI de Claude Code instalada. No secuestra OAuth, no extrae ni reutiliza tokens del navegador, no se hace pasar por un cliente no admitido ni omite la autenticación de Anthropic. Se mantiene en la vía de acceso admitida por Anthropic, por lo que no conlleva el riesgo de baneo asociado al secuestro de tokens o a rodeos de autenticación no autorizados. + +## Command Code + +Command Code usa tu plan de Command Code. + +1. Instala la integración (arriba). +2. Elige **Set up** — se abre una página en el navegador. Autoriza el acceso y vuelve a OpenChamber. + +En una máquina sin interfaz gráfica o en CI, define la variable de entorno `COMMAND_CODE_API_KEY` en lugar de iniciar sesión en el navegador. + +## Cursor + +Cursor hace disponibles en OpenChamber los modelos incluidos en tu plan de Cursor. + +1. Instala la integración (arriba). +2. Elige **Set up**, abre el enlace y autoriza el acceso en tu navegador. No necesitas clave de API. La lista de modelos se carga automáticamente tras iniciar sesión. + +## Actualizar o eliminar + +- **Update** instala la última versión publicada del plugin. +- **Remove** elimina el plugin de tu configuración de OpenCode. El proveedor deja de cargarse cuando OpenCode se recarga. + +Si una tarjeta indica que las entradas requieren gestión manual, elige **Manage plugins** y limpia ahí los duplicados. + +## Relacionado + +- [Proveedores, modelos y agentes](/es/providers/) — conecta otros proveedores y elige modelos +- [Uso y cuotas](/es/usage/) — sigue cuánto has usado diff --git a/packages/docs/content/docs/es/providers.mdx b/packages/docs/content/docs/es/providers.mdx index e6df93d2..24e5b94f 100644 --- a/packages/docs/content/docs/es/providers.mdx +++ b/packages/docs/content/docs/es/providers.mdx @@ -45,5 +45,6 @@ Los inicios de sesión de los proveedores los guarda OpenCode, no OpenChamber, a ## Relacionado +- [Integraciones](/es/integrations/) — usa una suscripción de Claude, Command Code o Cursor como proveedor - [Servidores MCP](/es/mcp/) — añade herramientas extra para los agentes - [Uso y cuotas](/es/usage/) — controla cuánto has consumido diff --git a/packages/docs/content/docs/es/skills-catalog.mdx b/packages/docs/content/docs/es/skills-catalog.mdx index 801874c2..c29ffb71 100644 --- a/packages/docs/content/docs/es/skills-catalog.mdx +++ b/packages/docs/content/docs/es/skills-catalog.mdx @@ -12,7 +12,7 @@ Para escribir tus propias skills, consulta [Skills](/es/skills/). ## Instala una skill 1. Abre el catálogo. -2. Explora las fuentes integradas —el repositorio de skills de Anthropic y el registro comunitario de ClawdHub— o busca. +2. Explora las fuentes integradas —como el repositorio de skills de Anthropic— o busca. 3. Elige una skill e instálala. 4. Elige dónde instalarla: para todo lo que hagas, o solo en el proyecto actual. diff --git a/packages/docs/content/docs/fr/integrations.mdx b/packages/docs/content/docs/fr/integrations.mdx new file mode 100644 index 00000000..df347a34 --- /dev/null +++ b/packages/docs/content/docs/fr/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Intégrations +description: Utilise ton abonnement Claude, Command Code ou Cursor comme fournisseur. +--- + +# Intégrations + +Une intégration est un petit plugin qui ajoute un fournisseur à OpenChamber à partir d'un abonnement que tu possèdes déjà. Tu les gères dans **Settings → Integrations**. + +Intégrations disponibles : + +- **Claude Code** — ton plan Claude Pro ou Max, sans clés API +- **Command Code** — ton plan Command Code +- **Cursor** — les limites de modèles de ton plan Cursor + +## Installer une intégration + +1. Ouvre **Settings → Integrations**. +2. Trouve l'intégration et choisis **Install**. +3. Redémarre OpenCode quand c'est demandé — le fournisseur apparaît après le redémarrage. +4. Choisis **Set up** et connecte-toi. Les modèles apparaissent ensuite dans le sélecteur de modèles du chat. + +Les intégrations s'installent pour ton utilisateur et fonctionnent donc dans tous les projets. Tu peux les mettre à jour ou les retirer à tout moment depuis la même carte. + +## Claude Code + +Claude Code utilise ton plan Claude Pro ou Max — sans clés API et sans application Claude séparée. + +1. Installe l'intégration (ci-dessus). +2. Choisis **Set up** et connecte-toi. Si tu n'as pas encore la CLI Claude Code, la configuration propose de l'installer d'abord, puis de te connecter. + +Claude Code est la seule intégration ici qui exige que la CLI de son fournisseur soit installée et connectée. Command Code et Cursor n'exigent pas leurs CLIs. + +**Comment ton compte Claude reste protégé :** cette intégration utilise le Claude Agent SDK officiel d'Anthropic et ta CLI Claude Code installée. Elle ne détourne pas l'OAuth, n'extrait ni rejoue de tokens de navigateur, ne se fait pas passer pour un client non pris en charge et ne contourne pas l'authentification d'Anthropic. Elle reste sur la voie d'accès prise en charge par Anthropic et ne porte donc pas le risque de bannissement associé au détournement de tokens ou aux contournements d'authentification non autorisés. + +## Command Code + +Command Code utilise ton plan Command Code. + +1. Installe l'intégration (ci-dessus). +2. Choisis **Set up** — une page s'ouvre dans le navigateur. Autorise l'accès, puis reviens dans OpenChamber. + +Sur une machine sans interface graphique ou en CI, définis la variable d'environnement `COMMAND_CODE_API_KEY` au lieu de te connecter via le navigateur. + +## Cursor + +Cursor rend disponibles dans OpenChamber les modèles inclus dans ton plan Cursor. + +1. Installe l'intégration (ci-dessus). +2. Choisis **Set up**, ouvre le lien et autorise l'accès dans ton navigateur. Aucune clé API n'est nécessaire. La liste des modèles se charge automatiquement après la connexion. + +## Mettre à jour ou retirer + +- **Update** installe la dernière version publiée du plugin. +- **Remove** supprime le plugin de ta configuration OpenCode. Le fournisseur cesse d'être chargé au prochain rechargement d'OpenCode. + +Si une carte indique que les entrées nécessitent une gestion manuelle, choisis **Manage plugins** et nettoie les doublons à cet endroit. + +## À voir aussi + +- [Fournisseurs, modèles et agents](/fr/providers/) — connecter d'autres fournisseurs et choisir des modèles +- [Utilisation et quotas](/fr/usage/) — suis ta consommation diff --git a/packages/docs/content/docs/fr/providers.mdx b/packages/docs/content/docs/fr/providers.mdx index dde4838e..d79633d8 100644 --- a/packages/docs/content/docs/fr/providers.mdx +++ b/packages/docs/content/docs/fr/providers.mdx @@ -45,5 +45,6 @@ Les connexions aux fournisseurs sont stockées par OpenCode, pas OpenChamber ; e ## Pages liées +- [Intégrations](/integrations/) — utiliser un abonnement Claude, Command Code ou Cursor comme fournisseur - [Serveurs MCP](/mcp/) — ajouter des outils supplémentaires aux agents - [Utilisation et quotas](/usage/) — suivre votre consommation diff --git a/packages/docs/content/docs/fr/skills-catalog.mdx b/packages/docs/content/docs/fr/skills-catalog.mdx index 4ccea878..e6eb2323 100644 --- a/packages/docs/content/docs/fr/skills-catalog.mdx +++ b/packages/docs/content/docs/fr/skills-catalog.mdx @@ -12,7 +12,7 @@ Pour écrire vos propres skills, voir [Skills](/skills/). ## Installer un skill 1. Ouvrez le catalogue. -2. Parcourez les sources intégrées — le dépôt de skills Anthropic et le registre communautaire ClawdHub — ou lancez une recherche. +2. Parcourez les sources intégrées — comme le dépôt de skills Anthropic — ou lancez une recherche. 3. Choisissez un skill et installez-le. 4. Choisissez où l’installer : pour tout ce que vous faites, ou seulement pour le projet actuel. diff --git a/packages/docs/content/docs/integrations.mdx b/packages/docs/content/docs/integrations.mdx new file mode 100644 index 00000000..14aee1f1 --- /dev/null +++ b/packages/docs/content/docs/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Integrations +description: Use your Claude, Command Code, or Cursor subscription as a provider. +--- + +# Integrations + +An integration is a small plugin that adds a provider to OpenChamber using a subscription you already have. You manage them at **Settings → Integrations**. + +Available integrations: + +- **Claude Code** — your Claude Pro or Max plan, no API keys +- **Command Code** — your Command Code plan +- **Cursor** — the model limits of your Cursor plan + +## Install an integration + +1. Open **Settings → Integrations**. +2. Find the integration and choose **Install**. +3. Restart OpenCode when asked — the provider appears after the restart. +4. Choose **Set up** and sign in. The models then appear in the chat model picker. + +Integrations install for your user, so they work in every project. You can update or remove them from the same card at any time. + +## Claude Code + +Claude Code uses your Claude Pro or Max plan — no API keys and no separate Claude app. + +1. Install the integration (above). +2. Choose **Set up** and sign in. If you don't have the Claude Code CLI yet, setup offers to install it first and then sign you in. + +Claude Code is the only integration here that requires its provider CLI to be installed and signed in. Command Code and Cursor do not require their CLIs. + +**How your Claude account stays safe:** this integration uses Anthropic's official Claude Agent SDK and your installed Claude Code CLI. It does not hijack OAuth, extract or replay browser tokens, impersonate an unsupported client, or bypass Anthropic's authentication flow. It stays on Anthropic's supported access path, so it does not carry the account-ban risk of token hijacking or unauthorized authentication workarounds. + +## Command Code + +Command Code uses your Command Code plan. + +1. Install the integration (above). +2. Choose **Set up** — a browser page opens. Approve access, then return to OpenChamber. + +On a headless machine or in CI, set the `COMMAND_CODE_API_KEY` environment variable instead of signing in in the browser. + +## Cursor + +Cursor makes the models included in your Cursor plan available in OpenChamber. + +1. Install the integration (above). +2. Choose **Set up**, open the link, and approve access in your browser. No API key is required. The model list loads automatically after you sign in. + +## Update or remove + +- **Update** installs the latest published version of the plugin. +- **Remove** deletes the plugin from your OpenCode config. The provider stops loading after OpenCode refreshes. + +If a card says the entries need manual management, choose **Manage plugins** and clean up the duplicates there. + +## Related + +- [Providers, Models & Agents](/providers/) — connect other providers and pick models +- [Usage & Quotas](/usage/) — track how much you've used diff --git a/packages/docs/content/docs/ja/integrations.mdx b/packages/docs/content/docs/ja/integrations.mdx new file mode 100644 index 00000000..02fa8e36 --- /dev/null +++ b/packages/docs/content/docs/ja/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: 統合機能 +description: Claude、Command Code、Cursor のサブスクリプションをプロバイダーとして使う。 +--- + +# 統合機能 + +統合機能(インテグレーション)は、すでに持っているサブスクリプションを使って OpenChamber にプロバイダーを追加する小さなプラグインです。**Settings → Integrations** で管理します。 + +利用できる統合機能: + +- **Claude Code** — Claude Pro または Max プラン、API キー不要 +- **Command Code** — Command Code のプラン +- **Cursor** — Cursor プランのモデル利用枠 + +## 統合機能をインストールする + +1. **Settings → Integrations** を開きます。 +2. 統合機能を見つけて **Install** を選びます。 +3. 求められたら OpenCode を再起動します — 再起動後にプロバイダーが現れます。 +4. **Set up** を選んでサインインします。するとチャットのモデル選択にモデルが表示されます。 + +統合機能はユーザー単位でインストールされるため、すべてのプロジェクトで使えます。同じカードからいつでも更新や削除ができます。 + +## Claude Code + +Claude Code は Claude Pro または Max プランを使います — API キーも Claude アプリも不要です。 + +1. 統合機能をインストールします(上記)。 +2. **Set up** を選んでサインインします。Claude Code CLI がまだない場合は、セットアップがまずインストールを提案し、その後サインインします。 + +Claude Code は、ここで唯一プロバイダーの CLI のインストールとサインインを必要とする統合機能です。Command Code と Cursor は CLI を必要としません。 + +**Claude アカウントが守られる仕組み:** この統合機能は Anthropic の公式 Claude Agent SDK と、インストール済みの Claude Code CLI を使用します。OAuth の乗っ取り、ブラウザートークンの抽出や再生、未対応クライアントへの偽装、Anthropic の認証フローの回避は一切行いません。Anthropic がサポートする正規のアクセス経路を使うため、トークン乗っ取りや不正な認証の回避につきもののアカウント停止リスクはありません。 + +## Command Code + +Command Code は Command Code のプランを使います。 + +1. 統合機能をインストールします(上記)。 +2. **Set up** を選ぶとブラウザーでページが開きます。アクセスを許可して OpenChamber に戻ります。 + +画面のないサーバーや CI では、ブラウザーでサインインする代わりに環境変数 `COMMAND_CODE_API_KEY` を設定してください。 + +## Cursor + +Cursor は Cursor プランに含まれるモデルを OpenChamber で使えるようにします。 + +1. 統合機能をインストールします(上記)。 +2. **Set up** を選び、リンクを開いてブラウザーでアクセスを許可します。API キーは不要です。サインイン後、モデル一覧は自動的に読み込まれます。 + +## 更新と削除 + +- **Update** はプラグインの最新の公開バージョンをインストールします。 +- **Remove** は OpenCode の設定からプラグインを削除します。OpenCode が再読み込みされるとプロバイダーは読み込まれなくなります。 + +カードに手動での管理が必要だと表示された場合は、**Manage plugins** を選んで重複を整理してください。 + +## 関連情報 + +- [プロバイダー、モデル、エージェント](/ja/providers/) — 他のプロバイダーの接続とモデルの選択 +- [使用量とクォータ](/ja/usage/) — 利用量を追跡 diff --git a/packages/docs/content/docs/ja/providers.mdx b/packages/docs/content/docs/ja/providers.mdx index 56b1616b..62f1c663 100644 --- a/packages/docs/content/docs/ja/providers.mdx +++ b/packages/docs/content/docs/ja/providers.mdx @@ -45,5 +45,6 @@ OpenChamber が何かを行うには、少なくとも 1 つの AI プロバイ ## 関連 +- [統合機能](/integrations/) — Claude、Command Code、Cursor のサブスクリプションをプロバイダーとして使う - [MCP サーバー](/mcp/) — エージェントに追加ツールを加える - [使用量とクォータ](/usage/) — 使った量を追跡する diff --git a/packages/docs/content/docs/ja/skills-catalog.mdx b/packages/docs/content/docs/ja/skills-catalog.mdx index c45fa791..029a0882 100644 --- a/packages/docs/content/docs/ja/skills-catalog.mdx +++ b/packages/docs/content/docs/ja/skills-catalog.mdx @@ -12,7 +12,7 @@ Skills Catalog では、自分で書く代わりに、他の人が公開した ## スキルをインストールする 1. カタログを開きます。 -2. 組み込みソース(Anthropic skills repo と ClawdHub community registry)を閲覧するか、検索します。 +2. 組み込みソース(Anthropic skills repo など)を閲覧するか、検索します。 3. スキルを選び、インストールします。 4. インストール先を選びます。すべての作業で使うか、現在のプロジェクトだけで使うかです。 diff --git a/packages/docs/content/docs/ko/integrations.mdx b/packages/docs/content/docs/ko/integrations.mdx new file mode 100644 index 00000000..f2589d50 --- /dev/null +++ b/packages/docs/content/docs/ko/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: 통합 기능 +description: Claude, Command Code 또는 Cursor 구독을 공급자로 사용하세요. +--- + +# 통합 기능 + +통합 기능(인테그레이션)은 이미 가지고 있는 구독을 사용해 OpenChamber에 공급자를 추가하는 작은 플러그인입니다. **Settings → Integrations**에서 관리합니다. + +사용 가능한 통합 기능: + +- **Claude Code** — Claude Pro 또는 Max 플랜, API 키 불필요 +- **Command Code** — Command Code 플랜 +- **Cursor** — Cursor 플랜의 모델 한도 + +## 통합 기능 설치 + +1. **Settings → Integrations**를 엽니다. +2. 통합 기능을 찾아 **Install**을 선택합니다. +3. 요청되면 OpenCode를 다시 시작합니다 — 재시작 후 공급자가 나타납니다. +4. **Set up**를 선택하고 로그인합니다. 그러면 채팅의 모델 선택기에 모델이 나타납니다. + +통합 기능은 사용자 단위로 설치되므로 모든 프로젝트에서 작동합니다. 같은 카드에서 언제든 업데이트하거나 제거할 수 있습니다. + +## Claude Code + +Claude Code는 Claude Pro 또는 Max 플랜을 사용합니다 — API 키도 별도의 Claude 앱도 필요 없습니다. + +1. 통합 기능을 설치합니다(위 참고). +2. **Set up**를 선택하고 로그인합니다. Claude Code CLI가 아직 없으면 설정에서 먼저 설치를 제안한 뒤 로그인을 진행합니다. + +Claude Code는 여기에서 유일하게 공급자 CLI 설치와 로그인을 필요로 하는 통합 기능입니다. Command Code와 Cursor는 CLI가 필요 없습니다. + +**Claude 계정이 안전하게 유지되는 방식:** 이 통합 기능은 Anthropic의 공식 Claude Agent SDK와 설치된 Claude Code CLI를 사용합니다. OAuth 탈취, 브라우저 토큰 추출·재사용, 지원되지 않는 클라이언트로의 위장, Anthropic 인증 우회를 하지 않습니다. Anthropic이 지원하는 정상 경로를 사용하므로 토큰 탈취나 비인가 인증 우회에 따른 계정 정지 위험이 없습니다. + +## Command Code + +Command Code는 Command Code 플랜을 사용합니다. + +1. 통합 기능을 설치합니다(위 참고). +2. **Set up**를 선택하면 브라우저에서 페이지가 열립니다. 접근을 승인한 뒤 OpenChamber로 돌아옵니다. + +화면이 없는 서버나 CI 환경에서는 브라우저 로그인 대신 `COMMAND_CODE_API_KEY` 환경 변수를 설정하세요. + +## Cursor + +Cursor는 Cursor 플랜에 포함된 모델을 OpenChamber에서 사용할 수 있게 합니다. + +1. 통합 기능을 설치합니다(위 참고). +2. **Set up**를 선택하고 링크를 열어 브라우저에서 접근을 승인합니다. API 키는 필요 없습니다. 로그인 후 모델 목록이 자동으로 로드됩니다. + +## 업데이트 및 제거 + +- **Update**는 플러그인의 최신 공개 버전을 설치합니다. +- **Remove**는 OpenCode 설정에서 플러그인을 삭제합니다. OpenCode가 다시 로드되면 공급자는 더 이상 로드되지 않습니다. + +카드에 항목을 수동으로 관리해야 한다고 표시되면 **Manage plugins**를 선택해 중복 항목을 정리하세요. + +## 관련 문서 + +- [공급자, 모델, 에이전트](/ko/providers/) — 다른 공급자 연결과 모델 선택 +- [사용량 및 할당량](/ko/usage/) — 사용량 추적 diff --git a/packages/docs/content/docs/ko/providers.mdx b/packages/docs/content/docs/ko/providers.mdx index 16869b26..11d9007f 100644 --- a/packages/docs/content/docs/ko/providers.mdx +++ b/packages/docs/content/docs/ko/providers.mdx @@ -45,5 +45,6 @@ OpenChamber가 무언가를 하려면 먼저 최소한 하나의 AI 공급자가 ## 관련 항목 +- [통합 기능](/ko/integrations/) — Claude, Command Code, Cursor 구독을 공급자로 사용 - [MCP Servers](/ko/mcp/) — 에이전트에 추가 도구를 제공합니다 - [Usage & Quotas](/ko/usage/) — 사용량을 추적합니다 diff --git a/packages/docs/content/docs/ko/skills-catalog.mdx b/packages/docs/content/docs/ko/skills-catalog.mdx index 664241a0..d2cbb407 100644 --- a/packages/docs/content/docs/ko/skills-catalog.mdx +++ b/packages/docs/content/docs/ko/skills-catalog.mdx @@ -12,7 +12,7 @@ Skills Catalog를 사용하면 직접 작성하는 대신 다른 사람이 게 ## 스킬 설치하기 1. 카탈로그를 엽니다. -2. 내장된 소스(Anthropic 스킬 저장소와 ClawdHub 커뮤니티 레지스트리)를 둘러보거나 검색합니다. +2. 내장된 소스(예: Anthropic 스킬 저장소)를 둘러보거나 검색합니다. 3. 스킬을 선택하고 설치합니다. 4. 설치 위치를 선택합니다. 모든 작업에 적용할지, 현재 프로젝트에만 적용할지 선택합니다. diff --git a/packages/docs/content/docs/pl/integrations.mdx b/packages/docs/content/docs/pl/integrations.mdx new file mode 100644 index 00000000..aca4b269 --- /dev/null +++ b/packages/docs/content/docs/pl/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Integracje +description: Używaj subskrypcji Claude, Command Code lub Cursor jako dostawcy. +--- + +# Integracje + +Integracja to mała wtyczka, która dodaje dostawcę do OpenChamber na podstawie subskrypcji, którą już masz. Zarządzasz nimi w **Settings → Integrations**. + +Dostępne integracje: + +- **Claude Code** — Twój plan Claude Pro lub Max, bez kluczy API +- **Command Code** — Twój plan Command Code +- **Cursor** — limity modeli z Twojego planu Cursor + +## Instalacja integracji + +1. Otwórz **Settings → Integrations**. +2. Znajdź integrację i wybierz **Install**. +3. Uruchom OpenCode ponownie, gdy o to poproszą — dostawca pojawi się po restarcie. +4. Wybierz **Set up** i zaloguj się. Modele pojawią się potem w selektorze modeli na czacie. + +Integracje instalują się dla Twojego użytkownika, więc działają w każdym projekcie. W każdej chwili możesz je zaktualizować lub usunąć z tej samej karty. + +## Claude Code + +Claude Code korzysta z Twojego planu Claude Pro lub Max — bez kluczy API i bez osobnej aplikacji Claude. + +1. Zainstaluj integrację (patrz wyżej). +2. Wybierz **Set up** i zaloguj się. Jeśli nie masz jeszcze Claude Code CLI, konfiguracja zaoferuje najpierw jego instalację, a potem logowanie. + +Claude Code jest jedyną integracją tutaj, która wymaga zainstalowanego i zalogowanego CLI swojego dostawcy. Command Code i Cursor nie wymagają swoich CLI. + +**Jak chronione jest Twoje konto Claude:** ta integracja używa oficjalnego Claude Agent SDK od Anthropic i Twojego zainstalowanego Claude Code CLI. Nie przechwytuje OAuth, nie wyodrębnia ani nie odtwarza tokenów przeglądarki, nie podszywa się pod nieobsługiwany klient i nie omija uwierzytelniania Anthropic. Działa na obsługiwanej przez Anthropic ścieżce dostępu, więc nie niesie ryzyka zablokowania konta związanego z przechwytywaniem tokenów lub nieautoryzowanymi obejściami uwierzytelniania. + +## Command Code + +Command Code korzysta z Twojego planu Command Code. + +1. Zainstaluj integrację (patrz wyżej). +2. Wybierz **Set up** — w przeglądarce otworzy się strona. Zatwierdź dostęp i wróć do OpenChamber. + +Na maszynie bez interfejsu graficznego lub w CI ustaw zmienną środowiskową `COMMAND_CODE_API_KEY` zamiast logowania w przeglądarce. + +## Cursor + +Cursor udostępnia w OpenChamber modele zawarte w Twoim planie Cursor. + +1. Zainstaluj integrację (patrz wyżej). +2. Wybierz **Set up**, otwórz link i zatwierdź dostęp w przeglądarce. Klucz API nie jest potrzebny. Lista modeli wczyta się automatycznie po zalogowaniu. + +## Aktualizacja i usuwanie + +- **Update** instaluje najnowszą opublikowaną wersję wtyczki. +- **Remove** usuwa wtyczkę z konfiguracji OpenCode. Dostawca przestanie się ładować po odświeżeniu OpenCode. + +Jeśli karta wskazuje, że wpisy wymagają ręcznego zarządzania, wybierz **Manage plugins** i wyczyść tam duplikaty. + +## Powiązane + +- [Dostawcy, modele i agenci](/pl/providers/) — podłączanie innych dostawców i wybór modeli +- [Zużycie i limity](/pl/usage/) — śledź, ile wykorzystałeś diff --git a/packages/docs/content/docs/pl/providers.mdx b/packages/docs/content/docs/pl/providers.mdx index 8675b91a..79d1ad41 100644 --- a/packages/docs/content/docs/pl/providers.mdx +++ b/packages/docs/content/docs/pl/providers.mdx @@ -45,5 +45,6 @@ Logowania dostawców są przechowywane przez OpenCode, a nie OpenChamber, więc ## Powiązane +- [Integracje](/pl/integrations/) — używaj subskrypcji Claude, Command Code lub Cursor jako dostawcy - [Serwery MCP](/pl/mcp/) — dodaj agentom dodatkowe narzędzia - [Zużycie i limity](/pl/usage/) — śledź, ile już wykorzystałeś diff --git a/packages/docs/content/docs/pl/skills-catalog.mdx b/packages/docs/content/docs/pl/skills-catalog.mdx index 56b3724f..d38a842f 100644 --- a/packages/docs/content/docs/pl/skills-catalog.mdx +++ b/packages/docs/content/docs/pl/skills-catalog.mdx @@ -12,7 +12,7 @@ Aby pisać własne skille, zobacz [Skille](/pl/skills/). ## Zainstaluj skill 1. Otwórz katalog. -2. Przeglądaj wbudowane źródła — repozytorium skilli Anthropic oraz rejestr społeczności ClawdHub — albo wyszukaj. +2. Przeglądaj wbudowane źródła — na przykład repozytorium skilli Anthropic — albo wyszukaj. 3. Wybierz skill i zainstaluj go. 4. Wybierz, gdzie go zainstalować: dla wszystkiego, co robisz, albo tylko dla bieżącego projektu. diff --git a/packages/docs/content/docs/providers.mdx b/packages/docs/content/docs/providers.mdx index 6b8a8e83..df7a7d1e 100644 --- a/packages/docs/content/docs/providers.mdx +++ b/packages/docs/content/docs/providers.mdx @@ -57,5 +57,6 @@ Provider sign-ins are stored by OpenCode, not OpenChamber, so they're shared wit ## Related +- [Integrations](/integrations/) — use a Claude, Command Code, or Cursor subscription as a provider - [MCP Servers](/mcp/) — add extra tools for agents - [Usage & Quotas](/usage/) — track how much you've used diff --git a/packages/docs/content/docs/pt-br/integrations.mdx b/packages/docs/content/docs/pt-br/integrations.mdx new file mode 100644 index 00000000..1d66cbda --- /dev/null +++ b/packages/docs/content/docs/pt-br/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Integrações +description: Use sua assinatura Claude, Command Code ou Cursor como provedor. +--- + +# Integrações + +Uma integração é um pequeno plugin que adiciona um provedor ao OpenChamber usando uma assinatura que você já tem. Você as gerencia em **Settings → Integrations**. + +Integrações disponíveis: + +- **Claude Code** — seu plano Claude Pro ou Max, sem chaves de API +- **Command Code** — seu plano Command Code +- **Cursor** — os limites de modelos do seu plano Cursor + +## Instalar uma integração + +1. Abra **Settings → Integrations**. +2. Encontre a integração e escolha **Install**. +3. Reinicie o OpenCode quando solicitado — o provedor aparece após a reinicialização. +4. Escolha **Set up** e faça login. Os modelos aparecem então no seletor de modelos do chat. + +As integrações são instaladas para o seu usuário, então funcionam em todos os projetos. Você pode atualizá-las ou removê-las do mesmo cartão a qualquer momento. + +## Claude Code + +O Claude Code usa seu plano Claude Pro ou Max — sem chaves de API e sem um app Claude separado. + +1. Instale a integração (acima). +2. Escolha **Set up** e faça login. Se você ainda não tem a CLI do Claude Code, a configuração oferece instalá-la primeiro e depois fazer login. + +O Claude Code é a única integração aqui que exige que a CLI do provedor esteja instalada e autenticada. Command Code e Cursor não exigem suas CLIs. + +**Como sua conta Claude fica protegida:** esta integração usa o Claude Agent SDK oficial da Anthropic e a CLI do Claude Code instalada em sua máquina. Ela não sequestra OAuth, não extrai nem reproduz tokens do navegador, não se passa por um cliente não suportado e não contorna a autenticação da Anthropic. Ela permanece no caminho de acesso suportado pela Anthropic, portanto não traz o risco de banimento de conta associado a sequestro de tokens ou a contornos de autenticação não autorizados. + +## Command Code + +O Command Code usa seu plano Command Code. + +1. Instale a integração (acima). +2. Escolha **Set up** — uma página abre no navegador. Autorize o acesso e volte ao OpenChamber. + +Em uma máquina sem interface gráfica ou em CI, defina a variável de ambiente `COMMAND_CODE_API_KEY` em vez de fazer login pelo navegador. + +## Cursor + +O Cursor torna disponíveis no OpenChamber os modelos incluídos no seu plano Cursor. + +1. Instale a integração (acima). +2. Escolha **Set up**, abra o link e autorize o acesso no navegador. Nenhuma chave de API é necessária. A lista de modelos carrega automaticamente após o login. + +## Atualizar ou remover + +- **Update** instala a versão publicada mais recente do plugin. +- **Remove** exclui o plugin da sua configuração do OpenCode. O provedor deixa de ser carregado quando o OpenCode é recarregado. + +Se um cartão indicar que as entradas precisam de gerenciamento manual, escolha **Manage plugins** e limpe as duplicatas lá. + +## Relacionado + +- [Provedores, modelos e agentes](/pt-br/providers/) — conecte outros provedores e escolha modelos +- [Uso e cotas](/pt-br/usage/) — acompanhe quanto você usou diff --git a/packages/docs/content/docs/pt-br/providers.mdx b/packages/docs/content/docs/pt-br/providers.mdx index 035002bc..b05dc222 100644 --- a/packages/docs/content/docs/pt-br/providers.mdx +++ b/packages/docs/content/docs/pt-br/providers.mdx @@ -45,5 +45,6 @@ Os logins de provedores são armazenados pelo OpenCode, não pelo OpenChamber, e ## Relacionado +- [Integrações](/pt-br/integrations/) — use uma assinatura Claude, Command Code ou Cursor como provedor - [Servidores MCP](/pt-br/mcp/) — adicione ferramentas extras para os agentes - [Uso e Cotas](/pt-br/usage/) — acompanhe quanto você já usou diff --git a/packages/docs/content/docs/pt-br/skills-catalog.mdx b/packages/docs/content/docs/pt-br/skills-catalog.mdx index 00adaa0f..b28c44f3 100644 --- a/packages/docs/content/docs/pt-br/skills-catalog.mdx +++ b/packages/docs/content/docs/pt-br/skills-catalog.mdx @@ -12,7 +12,7 @@ Para escrever suas próprias skills, veja [Skills](/pt-br/skills/). ## Instalar uma skill 1. Abra o catálogo. -2. Navegue pelas fontes integradas — o repositório de skills da Anthropic e o registro comunitário ClawdHub — ou pesquise. +2. Navegue pelas fontes integradas — como o repositório de skills da Anthropic — ou pesquise. 3. Escolha uma skill e instale-a. 4. Escolha onde instalá-la: para tudo o que você faz, ou apenas no projeto atual. diff --git a/packages/docs/content/docs/skills-catalog.mdx b/packages/docs/content/docs/skills-catalog.mdx index 381a878b..e223a459 100644 --- a/packages/docs/content/docs/skills-catalog.mdx +++ b/packages/docs/content/docs/skills-catalog.mdx @@ -12,7 +12,7 @@ For writing your own skills, see [Skills](/skills/). ## Install a skill 1. Open the catalog. -2. Browse the built-in sources — the Anthropic skills repo and the ClawdHub community registry — or search. +2. Browse the built-in sources — like the Anthropic skills repo — or search. 3. Pick a skill and install it. 4. Choose where to install it: for everything you do, or just the current project. diff --git a/packages/docs/content/docs/uk/integrations.mdx b/packages/docs/content/docs/uk/integrations.mdx new file mode 100644 index 00000000..b68da46c --- /dev/null +++ b/packages/docs/content/docs/uk/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: Інтеграції +description: Використовуйте підписки Claude, Command Code або Cursor як провайдерів. +--- + +# Інтеграції + +Інтеграція — це невеликий плагін, що додає провайдера до OpenChamber на основі підписки, яка в вас уже є. Керувати ними можна в **Settings → Integrations**. + +Доступні інтеграції: + +- **Claude Code** — ваша підписка Claude Pro або Max, без API-ключів +- **Command Code** — ваша підписка Command Code +- **Cursor** — ліміти моделей вашої підписки Cursor + +## Встановлення інтеграції + +1. Відкрийте **Settings → Integrations**. +2. Знайдіть інтеграцію та натисніть **Install**. +3. Перезапустіть OpenCode, коли про це попросять, — провайдер з'явиться після перезапуску. +4. Натисніть **Set up** і увійдіть. Після цього моделі з'являться в перемикачі моделей у чаті. + +Інтеграції встановлюються для вашого користувача, тож працюють у всіх проєктах. Оновити або видалити їх можна в будь-який момент з тієї ж карточки. + +## Claude Code + +Claude Code використовує вашу підписку Claude Pro або Max — без API-ключів і без окремого застосунку Claude. + +1. Встановіть інтеграцію (вище). +2. Натисніть **Set up** і увійдіть. Якщо у вас ще немає Claude Code CLI, програма встановлення спершу запропонує його встановити, а потім виконає вхід. + +Claude Code — єдина інтеграція тут, яка вимагає встановленого та залогіненого CLI свого провайдера. Для Command Code і Cursor їхні CLI не потрібні. + +**Як захищається ваш обліковий запис Claude:** ця інтеграція використовує офіційний Claude Agent SDK від Anthropic і ваш встановлений Claude Code CLI. Вона не перехоплює OAuth, не витягує й не відтворює браузерні токени, не видає себе за непідтримуваний клієнт і не обходить процес автентифікації Anthropic. Усе працює через підтримуваний Anthropic шлях доступу, тож інтеграція не несе ризику блокування облікового запису, пов'язаного з перехопленням токенів або несанкціонованими способами автентифікації. + +## Command Code + +Command Code використовує вашу підписку Command Code. + +1. Встановіть інтеграцію (вище). +2. Натисніть **Set up** — відкриється сторінка в браузері. Підтвердьте доступ і поверніться до OpenChamber. + +На сервері без графічного інтерфейсу або в CI замість входу через браузер задайте змінну середовища `COMMAND_CODE_API_KEY`. + +## Cursor + +Cursor робить доступними в OpenChamber моделі, що входять у вашу підписку Cursor. + +1. Встановіть інтеграцію (вище). +2. Натисніть **Set up**, відкрийте посилання та підтвердьте доступ у браузері. API-ключ не потрібен. Список моделей завантажиться автоматично після входу. + +## Оновлення та видалення + +- **Update** встановлює найновішу опубліковану версію плагіна. +- **Remove** видаляє плагін із конфігурації OpenCode. Провайдер перестане завантажуватися після оновлення OpenCode. + +Якщо карточка повідомляє, що записи потребують ручного керування, натисніть **Manage plugins** і приберіть дублікати там. + +## Пов'язане + +- [Провайдери, моделі та агенти](/uk/providers/) — підключення інших провайдерів і вибір моделей +- [Використання та квоти](/uk/usage/) — відстежуйте, скільки ви витратили diff --git a/packages/docs/content/docs/uk/providers.mdx b/packages/docs/content/docs/uk/providers.mdx index 693e15a7..4fb61d65 100644 --- a/packages/docs/content/docs/uk/providers.mdx +++ b/packages/docs/content/docs/uk/providers.mdx @@ -45,5 +45,6 @@ description: Підключайте AI-провайдерів, обирайте ## Пов'язане +- [Інтеграції](/uk/integrations/) — використовуйте підписки Claude, Command Code або Cursor як провайдерів - [MCP Servers](/uk/mcp/) — додайте агентам додаткові інструменти - [Використання та квоти](/uk/usage/) — відстежуйте, скільки ви витратили diff --git a/packages/docs/content/docs/uk/skills-catalog.mdx b/packages/docs/content/docs/uk/skills-catalog.mdx index 732abeb4..585ad77a 100644 --- a/packages/docs/content/docs/uk/skills-catalog.mdx +++ b/packages/docs/content/docs/uk/skills-catalog.mdx @@ -12,7 +12,7 @@ description: Переглядайте та встановлюйте готові ## Встановлення навички 1. Відкрийте каталог. -2. Перегляньте вбудовані джерела — репозиторій навичок Anthropic та спільнотний реєстр ClawdHub — або скористайтеся пошуком. +2. Перегляньте вбудовані джерела — наприклад репозиторій навичок Anthropic — або скористайтеся пошуком. 3. Оберіть навичку й установіть її. 4. Виберіть, куди встановити: для всього, що ви робите, чи лише для поточного проєкту. diff --git a/packages/docs/content/docs/zh-cn/integrations.mdx b/packages/docs/content/docs/zh-cn/integrations.mdx new file mode 100644 index 00000000..94daf884 --- /dev/null +++ b/packages/docs/content/docs/zh-cn/integrations.mdx @@ -0,0 +1,62 @@ +--- +title: 集成 +description: 将你的 Claude、Command Code 或 Cursor 订阅用作提供商。 +--- + +# 集成 + +集成是一个小型插件,它使用你已有的订阅为 OpenChamber 添加一个提供商。你可以在 **Settings → Integrations** 中管理它们。 + +可用的集成: + +- **Claude Code** — 你的 Claude Pro 或 Max 套餐,无需 API 密钥 +- **Command Code** — 你的 Command Code 套餐 +- **Cursor** — 你的 Cursor 套餐的模型额度 + +## 安装集成 + +1. 打开 **Settings → Integrations**。 +2. 找到所需的集成并选择 **Install**。 +3. 在提示时重启 OpenCode — 重启后提供商就会出现。 +4. 选择 **Set up** 并登录。之后模型会出现在聊天室的模型选择器中。 + +集成按用户安装,因此在所有项目中都可用。你可以随时在同一张卡片上更新或移除它们。 + +## Claude Code + +Claude Code 使用你的 Claude Pro 或 Max 套餐 — 无需 API 密钥,也无需单独的 Claude 应用。 + +1. 安装集成(见上文)。 +2. 选择 **Set up** 并登录。如果你还没有 Claude Code CLI,安装向导会先提供安装,然后再登录。 + +Claude Code 是这里唯一要求安装并登录其提供商 CLI 的集成。Command Code 和 Cursor 不需要它们的 CLI。 + +**你的 Claude 账户如何受到保护:** 此集成使用 Anthropic 官方的 Claude Agent SDK 和你已安装的 Claude Code CLI。它不会劫持 OAuth,不会提取或重放浏览器令牌,不会冒充不受支持的客户端,也不会绕过 Anthropic 的身份验证。它始终运行在 Anthropic 支持的访问路径上,因此不会带来与令牌劫持或未授权身份验证变通手段相关的封号风险。 + +## Command Code + +Command Code 使用你的 Command Code 套餐。 + +1. 安装集成(见上文)。 +2. 选择 **Set up** — 浏览器中会打开一个页面。授权访问,然后返回 OpenChamber。 + +在没有图形界面的服务器或 CI 环境中,请设置环境变量 `COMMAND_CODE_API_KEY` 来代替浏览器登录。 + +## Cursor + +Cursor 让你的 Cursor 套餐中包含的模型可以在 OpenChamber 中使用。 + +1. 安装集成(见上文)。 +2. 选择 **Set up**,打开链接并在浏览器中授权访问。无需 API 密钥。登录后模型列表会自动加载。 + +## 更新或移除 + +- **Update** 安装插件的最新发布版本。 +- **Remove** 从你的 OpenCode 配置中删除该插件。OpenCode 重新加载后,该提供商将不再加载。 + +如果卡片提示条目需要手动管理,请选择 **Manage plugins** 并在那里清理重复项。 + +## 相关内容 + +- [提供商、模型与智能体](/zh-cn/providers/) — 连接其他提供商并选择模型 +- [用量与配额](/zh-cn/usage/) — 跟踪你的使用量 diff --git a/packages/docs/content/docs/zh-cn/providers.mdx b/packages/docs/content/docs/zh-cn/providers.mdx index 8e92afd0..62cf4019 100644 --- a/packages/docs/content/docs/zh-cn/providers.mdx +++ b/packages/docs/content/docs/zh-cn/providers.mdx @@ -45,5 +45,6 @@ description: 连接 AI 提供商、选择模型并设置智能体。 ## 相关内容 +- [集成](/zh-cn/integrations/) — 将 Claude、Command Code 或 Cursor 订阅用作提供商 - [MCP Servers](/zh-cn/mcp/) — 为智能体添加额外工具 - [用量与配额](/zh-cn/usage/) — 跟踪你已使用的量 diff --git a/packages/docs/content/docs/zh-cn/skills-catalog.mdx b/packages/docs/content/docs/zh-cn/skills-catalog.mdx index f17f2a05..a3d982b1 100644 --- a/packages/docs/content/docs/zh-cn/skills-catalog.mdx +++ b/packages/docs/content/docs/zh-cn/skills-catalog.mdx @@ -12,7 +12,7 @@ Skills 目录让你能够安装其他人发布的 skill,而不必自己编写 ## 安装 skill 1. 打开目录。 -2. 浏览内置来源 — Anthropic skills 仓库和 ClawdHub 社区注册表 — 或进行搜索。 +2. 浏览内置来源 — 例如 Anthropic skills 仓库 — 或进行搜索。 3. 选择一个 skill 并安装它。 4. 选择安装位置:用于你的所有工作,或仅用于当前项目。 diff --git a/packages/docs/sidebar.config.json b/packages/docs/sidebar.config.json index 336241f8..137bbd5b 100644 --- a/packages/docs/sidebar.config.json +++ b/packages/docs/sidebar.config.json @@ -349,6 +349,21 @@ "de": "Anbieter, Modelle und Agenten" } }, + { + "label": "Integrations", + "link": "/integrations/", + "translations": { + "uk": "Інтеграції", + "zh-CN": "集成", + "es": "Integraciones", + "pt-BR": "Integrações", + "ko": "통합 기능", + "pl": "Integracje", + "fr": "Intégrations", + "ja": "統合機能", + "de": "Integrationen" + } + }, { "label": "MCP Servers", "link": "/mcp/", diff --git a/packages/electron/README.md b/packages/electron/README.md index abda712a..a7763d48 100644 --- a/packages/electron/README.md +++ b/packages/electron/README.md @@ -159,7 +159,9 @@ Use an explicit override when testing a different OpenCode CLI build or when a u grants permission requests by default when no handler is set, and the panel loads whatever address the user types. Tab favicons are fetched in this session too, so icons behind the page's own login resolve and the app's origin - never requests anything from a third-party host. + never requests anything from a third-party host. Self-signed loopback HTTPS + pages may use an untrusted certificate authority; certificate failures for + external hosts and all other certificate errors remain blocked. ## IPC Pattern diff --git a/packages/electron/browser-panel-security.mjs b/packages/electron/browser-panel-security.mjs new file mode 100644 index 00000000..532148d2 --- /dev/null +++ b/packages/electron/browser-panel-security.mjs @@ -0,0 +1,12 @@ +const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']); + +export const shouldAllowBrowserPanelCertificateError = ({ url, error }) => { + if (error !== 'net::ERR_CERT_AUTHORITY_INVALID') return false; + + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' && LOOPBACK_HOSTNAMES.has(parsed.hostname.toLowerCase()); + } catch { + return false; + } +}; diff --git a/packages/electron/browser-panel-security.test.mjs b/packages/electron/browser-panel-security.test.mjs new file mode 100644 index 00000000..a81a9e87 --- /dev/null +++ b/packages/electron/browser-panel-security.test.mjs @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { shouldAllowBrowserPanelCertificateError } from './browser-panel-security.mjs'; + +test('allows untrusted certificate authorities for loopback HTTPS pages', () => { + for (const url of [ + 'https://localhost:58580/', + 'https://127.0.0.1:58580/', + 'https://[::1]:58580/', + ]) { + assert.equal(shouldAllowBrowserPanelCertificateError({ + url, + error: 'net::ERR_CERT_AUTHORITY_INVALID', + }), true); + } +}); + +test('keeps certificate validation for non-loopback pages', () => { + for (const url of [ + 'https://example.com/', + 'https://localhost.example.com/', + 'https://0.0.0.0:58580/', + ]) { + assert.equal(shouldAllowBrowserPanelCertificateError({ + url, + error: 'net::ERR_CERT_AUTHORITY_INVALID', + }), false); + } +}); + +test('does not bypass other certificate failures or malformed URLs', () => { + assert.equal(shouldAllowBrowserPanelCertificateError({ + url: 'https://localhost:58580/', + error: 'net::ERR_CERT_DATE_INVALID', + }), false); + assert.equal(shouldAllowBrowserPanelCertificateError({ + url: 'not a url', + error: 'net::ERR_CERT_AUTHORITY_INVALID', + }), false); +}); diff --git a/packages/electron/main.mjs b/packages/electron/main.mjs index 0bcc1de9..46805505 100644 --- a/packages/electron/main.mjs +++ b/packages/electron/main.mjs @@ -31,6 +31,7 @@ import { setLinuxAutostartEnabled, } from './linux-autostart.mjs'; import { unsupportedAppSpecificOpenError, validateLocalPath } from './path-open-utils.mjs'; +import { shouldAllowBrowserPanelCertificateError } from './browser-panel-security.mjs'; import { mintOutsideFileGrant } from '@openchamber/web/server/lib/fs/routes.js'; const execFileAsync = promisify(execFile); @@ -1186,6 +1187,15 @@ const resolveBrowserPanelContents = (rawId) => { const hardenBrowserPanelSession = () => { const panelSession = session.fromPartition(BROWSER_PANEL_PARTITION); + app.on('certificate-error', (event, contents, url, error, _certificate, callback) => { + if (contents.session === panelSession && shouldAllowBrowserPanelCertificateError({ url, error })) { + event.preventDefault(); + callback(true); + return; + } + callback(false); + }); + panelSession.setPermissionRequestHandler((_contents, permission, callback, details) => { log.info('[electron] browser panel denied a permission request', { permission, @@ -2455,6 +2465,9 @@ const createBrowserWindow = ({ label, restoreGeometry, url, runtimeConfig = {} } browserWindow.__ocRuntimeConfig = { apiBaseUrl: desktopApiBaseUrl, clientToken: desktopClientToken, requestHeaders: desktopRequestHeaders }; browserWindow.__ocInitScript = buildInitScript(desktopLocalOrigin, state.bootOutcome, desktopApiBaseUrl, desktopClientToken, desktopRequestHeaders); browserWindow.__ocTitleBarOverlayEnabled = titleBarOverlayEnabled; + browserWindow.on('app-command', (event, command) => { + if (command === 'browser-backward') event.preventDefault(); + }); if (useSaved && saved.maximized) { browserWindow.maximize(); diff --git a/packages/electron/package.json b/packages/electron/package.json index 9a189fe5..8432487f 100644 --- a/packages/electron/package.json +++ b/packages/electron/package.json @@ -1,6 +1,6 @@ { "name": "@openchamber/electron", - "version": "1.18.3", + "version": "1.19.0", "private": true, "description": "Electron desktop runtime for OpenChamber", "author": "OpenChamber", diff --git a/packages/ui/package.json b/packages/ui/package.json index ea998370..2b224dcb 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@openchamber/ui", - "version": "1.18.3", + "version": "1.19.0", "private": true, "type": "module", "main": "src/main.tsx", @@ -19,34 +19,34 @@ "@capacitor/keyboard": "^8.0.0", "@capacitor/push-notifications": "^8.1.1", "@capacitor/status-bar": "^8.0.0", - "@codemirror/autocomplete": "^6.20.0", - "@codemirror/commands": "^6.10.1", + "@codemirror/autocomplete": "^6.20.3", + "@codemirror/commands": "^6.11.0", "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-css": "^6.3.1", "@codemirror/lang-go": "^6.0.1", - "@codemirror/lang-html": "^6.4.11", - "@codemirror/lang-javascript": "^6.2.4", + "@codemirror/lang-html": "^6.4.12", + "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", - "@codemirror/lang-markdown": "^6.5.0", + "@codemirror/lang-markdown": "^6.5.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/lang-rust": "^6.0.2", "@codemirror/lang-sql": "^6.10.0", "@codemirror/lang-xml": "^6.1.0", - "@codemirror/lang-yaml": "^6.1.2", - "@codemirror/language": "6.12.2", + "@codemirror/lang-yaml": "^6.1.3", + "@codemirror/language": "6.12.4", "@codemirror/language-data": "^6.5.2", - "@codemirror/legacy-modes": "^6.5.2", - "@codemirror/lint": "^6.9.2", - "@codemirror/search": "^6.6.0", - "@codemirror/state": "^6.5.4", - "@codemirror/view": "6.39.13", + "@codemirror/legacy-modes": "^6.5.3", + "@codemirror/lint": "^6.9.7", + "@codemirror/search": "^6.7.1", + "@codemirror/state": "^6.7.1", + "@codemirror/view": "6.43.9", "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", "@lezer/highlight": "^1.2.3", "@opencode-ai/sdk": "1.18.18", "@pierre/diffs": "1.3.0-beta.6", - "@replit/codemirror-vim": "^6.3.0", + "@replit/codemirror-vim": "^6.4.0", "@simplewebauthn/browser": "13.3.0", "@tanstack/react-virtual": "3.14.5", "@xenova/transformers": "^2.17.2", diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index 7c4d3d07..ff0ffe7c 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -14,6 +14,7 @@ import { useTraySync } from '@/hooks/useTraySync'; import { useRouter } from '@/hooks/useRouter'; import { usePushVisibilityBeacon } from '@/hooks/usePushVisibilityBeacon'; import { useWebNotificationStream } from '@/hooks/useWebNotificationStream'; +import { useAgentMemorySync } from '@/hooks/useAgentMemorySync'; import { usePwaInstallPrompt } from '@/hooks/usePwaInstallPrompt'; import { useWindowTitle } from '@/hooks/useWindowTitle'; import { useConfigStore } from '@/stores/useConfigStore'; @@ -54,7 +55,11 @@ import { MCP_OAUTH_CALLBACK_PATH } from '@/components/sections/mcp/mcpOAuth'; import { lazyWithChunkRecovery } from '@/lib/chunkLoadRecovery'; import { useI18n } from '@/lib/i18n'; import { applyMobileKeyboardMode } from '@/lib/mobileKeyboardMode'; -import { isEmbeddedSessionChat } from '@/components/layout/contextPanelEmbeddedChat'; +import { + EMBEDDED_VISIBILITY_UPDATE, + isEmbeddedSessionChat, + requestEmbeddedSessionVisibility, +} from '@/components/layout/contextPanelEmbeddedChat'; import { SyncAppEffects } from '@/apps/AppEffects'; import { resetAppForRuntimeEndpointChange } from '@/apps/runtimeEndpointReset'; import { useAppFontEffects } from '@/apps/useAppFontEffects'; @@ -205,6 +210,11 @@ const EmbeddedSessionChatContent: React.FC<{ @@ -538,17 +548,16 @@ function App({ apis }: AppProps) { } const applyVisibility = (payload?: EmbeddedVisibilityPayload) => { - const nextVisible = payload?.visible === true; - setIsEmbeddedVisible(nextVisible); + setIsEmbeddedVisible(payload?.visible === true); }; const handleMessage = (event: MessageEvent) => { - if (event.origin !== window.location.origin) { + if (event.origin !== window.location.origin || event.source !== window.parent) { return; } const data = event.data as { type?: unknown; payload?: EmbeddedVisibilityPayload }; - if (data?.type !== 'openchamber:embedded-visibility') { + if (data?.type !== EMBEDDED_VISIBILITY_UPDATE) { return; } @@ -561,6 +570,7 @@ function App({ apis }: AppProps) { scopedWindow.__openchamberSetEmbeddedVisibility = applyVisibility; window.addEventListener('message', handleMessage); + requestEmbeddedSessionVisibility(); return () => { window.removeEventListener('message', handleMessage); @@ -694,6 +704,10 @@ function App({ apis }: AppProps) { usePushVisibilityBeacon({ enabled: embeddedBackgroundWorkEnabled }); useWebNotificationStream({ enabled: embeddedBackgroundWorkEnabled }); + // Loaded here rather than by the Memory tab: the session index is built from + // this snapshot, so leaving it to the panel meant a user who never opened + // Project notes sent every message with no memory index at all. + useAgentMemorySync(currentDirectory || null); usePwaInstallPrompt(); useWindowTitle(); diff --git a/packages/ui/src/apps/MobileApp.tsx b/packages/ui/src/apps/MobileApp.tsx index 0880639f..b790270c 100644 --- a/packages/ui/src/apps/MobileApp.tsx +++ b/packages/ui/src/apps/MobileApp.tsx @@ -83,6 +83,7 @@ const MOBILE_SETTINGS_PAGES = [ 'providers', 'usage', 'voice', + 'integrations', 'about', ] as const; @@ -108,7 +109,7 @@ const MobileShell: React.FC<{ onActiveConnectionDeleted: () => void }> = ({ onAc const [workspaceTab, setWorkspaceTab] = React.useState('changes'); // A plan opened from the workspace drawer's Notes tab, shown as a fullscreen // layer on top of it (back returns to the notes). - const [openPlan, setOpenPlan] = React.useState<{ path: string; title: string } | null>(null); + const [openPlan, setOpenPlan] = React.useState<{ id: string; title: string } | null>(null); const [settingsInitialMobileStage, setSettingsInitialMobileStage] = React.useState<'nav' | 'page-content'>('nav'); // When set, the Changes surface opens directly into the per-file diff for this path. const [pendingChangesDiff, setPendingChangesDiff] = React.useState<{ path: string; staged: boolean } | null>(null); @@ -539,7 +540,7 @@ const MobileShell: React.FC<{ onActiveConnectionDeleted: () => void }> = ({ onAc > { closeSurface(); closeWorkspace(); diff --git a/packages/ui/src/apps/MobileSessionMetadata.tsx b/packages/ui/src/apps/MobileSessionMetadata.tsx index 9ffe0d66..3d239d1f 100644 --- a/packages/ui/src/apps/MobileSessionMetadata.tsx +++ b/packages/ui/src/apps/MobileSessionMetadata.tsx @@ -388,6 +388,7 @@ export const MobileSessionMetadataButton = React.memo(function MobileSessionMeta for (let i = activeSessionMessages.length - 1; i >= 0; i -= 1) { const message = activeSessionMessages[i] as typeof activeSessionMessages[number] & { tokens?: { + total?: unknown; input?: unknown; output?: unknown; reasoning?: unknown; @@ -395,6 +396,11 @@ export const MobileSessionMetadataButton = React.memo(function MobileSessionMeta }; }; if (message.role !== 'assistant' || !message.tokens) continue; + // Multi-step turns accumulate the fields across API round-trips, so + // summing them overstates the window. The server-reported total is the + // final round-trip's window; sum only when the server did not send it. + const reportedTotal = getTokenCount(message.tokens.total); + if (reportedTotal > 0) return reportedTotal; const total = getTokenCount(message.tokens.input) + getTokenCount(message.tokens.output) + getTokenCount(message.tokens.reasoning) diff --git a/packages/ui/src/apps/MobileWorkspaceDrawer.tsx b/packages/ui/src/apps/MobileWorkspaceDrawer.tsx index b3c94c24..f0847aa1 100644 --- a/packages/ui/src/apps/MobileWorkspaceDrawer.tsx +++ b/packages/ui/src/apps/MobileWorkspaceDrawer.tsx @@ -105,7 +105,7 @@ export const MobileWorkspaceDrawer: React.FC<{ /** When set, the Changes tab opens directly into the per-file diff. */ pendingChangesDiff: { path: string; staged: boolean } | null; /** Notes tab: opens a plan fullscreen (layered above the drawer). */ - onOpenPlan: (plan: { path: string; title: string }) => void; + onOpenPlan: (plan: { id: string; title: string }) => void; /** MCP tab: jump to the MCP settings page pre-seeded with a new server draft. */ onOpenMcpSettings: () => void; variant?: 'drawer' | 'panel'; diff --git a/packages/ui/src/apps/mobileConnections.ts b/packages/ui/src/apps/mobileConnections.ts index 30ba5d8f..78b5851b 100644 --- a/packages/ui/src/apps/mobileConnections.ts +++ b/packages/ui/src/apps/mobileConnections.ts @@ -23,7 +23,7 @@ import type { PairingConnectionPayload, PairingEndpointCandidate } from '@/lib/c import { isCapacitorApp } from '@/lib/platform'; import { adoptRelayTunnel, isRelayModeActive } from '@/lib/relay/runtime-tunnel'; import { createRelayTunnelClient } from '@/lib/relay/tunnel-client'; -import { runtimeFetch } from '@/lib/runtime-fetch'; +import { addRuntimeProxyHeaders, runtimeFetch } from '@/lib/runtime-fetch'; import { getRuntimeApiBaseUrl, getRuntimeKey, switchRuntimeEndpoint } from '@/lib/runtime-switch'; import { recordMobileConnectDebug } from './mobileConnectionDebug'; @@ -346,11 +346,11 @@ const nativeHttpRequest = async (url: string, init?: RequestInit): Promise c.kind), fast }); + logConnect('reprobe:start', { candidates: active.candidates.map((c) => c.kind), fast, hasToken: Boolean(token) }); const currentIndex = active.candidates.findIndex( (candidate) => transportMatchesCurrentRuntime(candidate.kind === 'relay' ? { kind: 'relay', relay: candidate.relay } : { kind: 'direct', url: candidate.url }), @@ -1225,7 +1229,7 @@ export const reprobeActiveConnection = async (options?: { fast?: boolean }): Pro logConnect('reprobe:better', { status: better.status, probed: higher.length }); if (better.status === 'ok') { await upsertMobileConnection({ id: active.id, label: active.label, candidates: active.candidates }); - switchToTransport(better.transport, token, { runtimeKey: secureTokenKeyOf(active) }); + switchToTransport(better.transport, token ?? null, { runtimeKey: secureTokenKeyOf(active) }); return 'switched'; } // The shared token was explicitly rejected — no transport will accept it. @@ -1251,7 +1255,7 @@ export const reprobeActiveConnection = async (options?: { fast?: boolean }): Pro logConnect('reprobe:fallback', { status: fallback.status, probed: lower.length }); if (fallback.status === 'ok') { await upsertMobileConnection({ id: active.id, label: active.label, candidates: active.candidates }); - switchToTransport(fallback.transport, token, { runtimeKey: secureTokenKeyOf(active) }); + switchToTransport(fallback.transport, token ?? null, { runtimeKey: secureTokenKeyOf(active) }); return 'switched'; } if (fallback.status === 'needs-login') return 'needs-login'; diff --git a/packages/ui/src/apps/runtimeEndpointReset.ts b/packages/ui/src/apps/runtimeEndpointReset.ts index b430cfc9..39c325fd 100644 --- a/packages/ui/src/apps/runtimeEndpointReset.ts +++ b/packages/ui/src/apps/runtimeEndpointReset.ts @@ -3,6 +3,7 @@ import type { RuntimeEndpointChangedDetail } from '@/lib/runtime-switch'; import { disposeTerminalInputTransport } from '@/lib/terminalApi'; import { useConfigStore } from '@/stores/useConfigStore'; import { useProjectsStore } from '@/stores/useProjectsStore'; +import { useProjectContextStore } from '@/stores/useProjectContextStore'; import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore'; import { useAutoReviewStore } from '@/stores/useAutoReviewStore'; import { useUIStore } from '@/stores/useUIStore'; @@ -52,6 +53,9 @@ export const resetAppForRuntimeEndpointChange = (detail: RuntimeEndpointChangedD lastDisconnectReason: null, }); useProjectsStore.getState().resetForRuntimeSwitch(); + // Notes, todos, plans and the pinned-context bookkeeping are keyed by a + // path-derived project id, which two runtimes can collide on. + useProjectContextStore.getState().reset(); // Cross-project session list (mobile sessions sheet & co) belongs to the // previous instance — drop it so stale sessions can't linger after a switch. useGlobalSessionsStore.getState().resetForRuntimeSwitch(); diff --git a/packages/ui/src/assets/provider-logos/claude-code.svg b/packages/ui/src/assets/provider-logos/claude-code.svg new file mode 100644 index 00000000..9a454303 --- /dev/null +++ b/packages/ui/src/assets/provider-logos/claude-code.svg @@ -0,0 +1,4 @@ + diff --git a/packages/ui/src/assets/provider-logos/command-code.svg b/packages/ui/src/assets/provider-logos/command-code.svg new file mode 100644 index 00000000..786e90bc --- /dev/null +++ b/packages/ui/src/assets/provider-logos/command-code.svg @@ -0,0 +1,15 @@ + + Command Code + + + diff --git a/packages/ui/src/components/browser/BrowserToolbar.tsx b/packages/ui/src/components/browser/BrowserToolbar.tsx index c56aca09..f2eaf046 100644 --- a/packages/ui/src/components/browser/BrowserToolbar.tsx +++ b/packages/ui/src/components/browser/BrowserToolbar.tsx @@ -226,7 +226,7 @@ export const BrowserToolbar: React.FC = ({ ) : null} {onAnnotate ? ( { type ChatContainerProps = { active?: boolean; + /** + * When set, controls message-history reads and session-message loads + * independently of `active`. Defaults to `active`. Embedded session-chat + * panels pass `true` so a delayed/lost visibility handshake cannot hide + * an already-materialized transcript (leaving only the working-status + * row — issue #2903). + */ + messagesEnabled?: boolean; autoOpenDraft?: boolean; readOnly?: boolean; initialAllowPromptingSubagentSessions?: boolean; }; -export const ChatContainer: React.FC = ({ active = true, autoOpenDraft = true, readOnly = false, initialAllowPromptingSubagentSessions }) => { +export const ChatContainer: React.FC = ({ + active = true, + messagesEnabled: messagesEnabledProp, + autoOpenDraft = true, + readOnly = false, + initialAllowPromptingSubagentSessions, +}) => { + const messagesEnabled = messagesEnabledProp ?? active; const { t } = useI18n(); // Session UI state const currentSessionId = useSessionUIStore((s) => s.currentSessionId); @@ -591,9 +606,11 @@ export const ChatContainer: React.FC = ({ active = true, aut ); const sessionMessageCount = useSessionMessageCount(currentSessionId ?? '', effectiveSessionDirectory); const hasRenderableSessionSnapshot = useSessionRenderable(currentSessionId ?? '', effectiveSessionDirectory); - // Messages from sync system + // Messages from sync system. Keep this gated by `messagesEnabled`, not + // `active`, so embedded panels can show history while the composer stays + // inactive until the parent confirms visibility. const sessionMessageRecords = useSessionMessageRecords(currentSessionId ?? '', effectiveSessionDirectory, { - enabled: active, + enabled: messagesEnabled, suspendPartUpdates: Boolean(streamingMessageId), suspendPartUpdatesForMessageId: streamingMessageId, }); @@ -1042,9 +1059,9 @@ export const ChatContainer: React.FC = ({ active = true, aut Boolean(currentSessionId) && !hasRenderableSessionSnapshot; const retrySessionLoad = React.useCallback(() => { - if (!active || !currentSessionId) return; + if (!messagesEnabled || !currentSessionId) return; void sync.ensureSessionRenderable(currentSessionId, true, effectiveSessionDirectory); - }, [active, currentSessionId, effectiveSessionDirectory, sync]); + }, [currentSessionId, effectiveSessionDirectory, messagesEnabled, sync]); React.useEffect(() => { if (!active || !currentSessionId) return; @@ -1069,10 +1086,10 @@ export const ChatContainer: React.FC = ({ active = true, aut }, [active, currentSessionId, currentSessionKey, releaseAutoFollow, restoreSnapshot]); React.useEffect(() => { - if (!active || !currentSessionId) return; + if (!messagesEnabled || !currentSessionId) return; if (hasRenderableSessionSnapshot) return; void ensureSessionRenderable(currentSessionId); - }, [active, currentSessionId, ensureSessionRenderable, hasRenderableSessionSnapshot]); + }, [currentSessionId, ensureSessionRenderable, hasRenderableSessionSnapshot, messagesEnabled]); if (!currentSessionId && !draftOpen) { // With auto-open, the draft welcome opens on the next tick (effect below), diff --git a/packages/ui/src/components/chat/ChatInput.tsx b/packages/ui/src/components/chat/ChatInput.tsx index 1df58ebb..06f73900 100644 --- a/packages/ui/src/components/chat/ChatInput.tsx +++ b/packages/ui/src/components/chat/ChatInput.tsx @@ -7,11 +7,12 @@ import { createMessageQueueTarget, getMessageQueueKey, useMessageQueueStore, typ import { useAutoReviewStore } from '@/stores/useAutoReviewStore'; import { useSessionUIStore } from '@/sync/session-ui-store'; import { useSelectionStore } from '@/sync/selection-store'; -import { useInputStore } from '@/sync/input-store'; +import { prepareLocalAttachments, useInputStore } from '@/sync/input-store'; import { ACCEPTED_ATTACHMENT_EXTENSIONS, ATTACHMENT_ACCEPT, getUnsupportedAttachmentInputs, + isDocumentAttachmentFilename, type AttachmentInputModality, } from '@/sync/attachment-files'; import type { AttachedFile } from '@/stores/types/sessionTypes'; @@ -24,6 +25,7 @@ import { appendInlineComments } from '@/lib/messages/inlineComments'; import { renderMagicPrompt } from '@/lib/magicPrompts'; import { startReviewFlow } from '@/lib/reviewFlow'; import { getRuntimeKey } from '@/lib/runtime-switch'; +import { runtimeFetch } from '@/lib/runtime-fetch'; import { createChatDraftIdentity, readChatDraft, @@ -596,59 +598,62 @@ const ChatInputComponent: React.FC = ({ onOpenSettings, scrollTo [], ); - const extractInlineFileMentions = React.useCallback((rawText: string): { sanitizedText: string; attachments: AttachedFile[] } => { + const resolveInlineFileMention = React.useCallback((mentionPath: string): { serverPath: string; filename: string } | null => { + const kind = classifyMention(mentionPath, { + knownAgentNames: knownAgentNamesRef.current, + confirmedMentions: confirmedMentionsRef.current, + }); + if (kind !== 'file') return null; + + const normalizedMentionPath = mentionPath.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, ''); + if (!normalizedMentionPath) return null; + + const clientDirectory = opencodeClient.getDirectory() || ''; + const root = (chatSearchDirectory || clientDirectory).replace(/\\/g, '/').replace(/\/+$/, ''); + let serverPath: string | null = null; + if (mentionPath.startsWith('/')) { + serverPath = mentionPath.replace(/\\/g, '/'); + } else if (root) { + serverPath = `${root}/${normalizedMentionPath}`; + } + if (!serverPath) return null; + + return { + serverPath: serverPath.replace(/\/+/g, '/'), + filename: normalizedMentionPath.split('/').filter(Boolean).pop() || normalizedMentionPath, + }; + }, [chatSearchDirectory]); + + const extractInlineFileMentions = React.useCallback(( + rawText: string, + preparedDocumentMentions?: ReadonlyMap, + ) => { if (!rawText || !rawText.includes('@')) { return { sanitizedText: rawText, attachments: [] }; } - const clientDirectory = opencodeClient.getDirectory() || ''; - const root = (chatSearchDirectory || clientDirectory).replace(/\\/g, '/').replace(/\/+$/, ''); const seenPaths = new Set(); const attachments: AttachedFile[] = []; for (const token of scanMentions(rawText)) { - const mentionPath = token.name; - const kind = classifyMention(mentionPath, { - knownAgentNames: knownAgentNamesRef.current, - confirmedMentions: confirmedMentionsRef.current, - }); - // Agents are routed separately by parseAgentMentions; only file - // references become attachments here. - if (kind !== 'file') { + const mention = resolveInlineFileMention(token.name); + if (!mention || seenPaths.has(mention.serverPath)) continue; + seenPaths.add(mention.serverPath); + + const prepared = preparedDocumentMentions?.get(mention.serverPath); + if (prepared) { + attachments.push(...prepared); continue; } - - const normalizedMentionPath = mentionPath.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, ''); - if (!normalizedMentionPath) { - continue; - } - - const serverPath = mentionPath.startsWith('/') - ? mentionPath.replace(/\\/g, '/') - : root - ? `${root}/${normalizedMentionPath}` - : null; - - if (!serverPath) { - continue; - } - - const normalizedServerPath = serverPath.replace(/\/+/g, '/'); - if (seenPaths.has(normalizedServerPath)) { - continue; - } - seenPaths.add(normalizedServerPath); - - const filename = normalizedMentionPath.split('/').filter(Boolean).pop() || normalizedMentionPath; attachments.push({ id: `inline-server-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`, - file: new File([], filename, { type: 'text/plain' }), - filename, + file: new File([], mention.filename, { type: 'text/plain' }), + filename: mention.filename, mimeType: 'text/plain', size: 0, - dataUrl: toServerFileUrl(normalizedServerPath), + dataUrl: toServerFileUrl(mention.serverPath), source: 'server', - serverPath: normalizedServerPath, + serverPath: mention.serverPath, }); } @@ -656,7 +661,7 @@ const ChatInputComponent: React.FC = ({ onOpenSettings, scrollTo sanitizedText: rawText, attachments, }; - }, [chatSearchDirectory]); + }, [resolveInlineFileMention]); const abortTimeoutRef = React.useRef | null>(null); const prevWasAbortedRef = React.useRef(false); @@ -960,6 +965,7 @@ const ChatInputComponent: React.FC = ({ onOpenSettings, scrollTo }; const handleSubmit = async (options?: SubmitOptions) => { + const submitRuntimeKey = getRuntimeKey(); const queuedOnly = options?.queuedOnly ?? false; const queuedMessageId = options?.queuedMessageId; const delivery = options?.delivery === 'steer' && sessionPhase !== 'idle' ? 'steer' : undefined; @@ -1051,6 +1057,44 @@ const ChatInputComponent: React.FC = ({ onOpenSettings, scrollTo } : undefined; + const preparedDocumentMentions = new Map(); + const reservedFilenames = new Set([ + ...attachedFiles.map((attachment) => attachment.filename), + ...queuedMessagesToSend.flatMap((queued) => queued.attachments?.map((attachment) => attachment.filename) ?? []), + ]); + const mentionTexts = [ + ...queuedMessagesToSend.map((queued) => queued.content), + ...(!queuedOnly && inputSnapshot.hasContent ? [inputSnapshot.message] : []), + ]; + for (const rawText of mentionTexts) { + for (const token of scanMentions(rawText)) { + const mention = resolveInlineFileMention(token.name); + if ( + !mention + || !isDocumentAttachmentFilename(mention.filename) + || preparedDocumentMentions.has(mention.serverPath) + ) { + continue; + } + try { + const response = await runtimeFetch('/api/fs/raw', { query: { path: mention.serverPath } }); + if (!response.ok) throw new Error(`Failed to read ${mention.filename}`); + const sourceBlob = await response.blob(); + if (getRuntimeKey() !== submitRuntimeKey) return; + const source = new File([sourceBlob], mention.filename); + const prepared = await prepareLocalAttachments(source, reservedFilenames); + if (!prepared || prepared.length === 0) throw new Error(`Failed to prepare ${mention.filename}`); + if (getRuntimeKey() !== submitRuntimeKey) return; + preparedDocumentMentions.set(mention.serverPath, prepared); + for (const attachment of prepared) reservedFilenames.add(attachment.filename); + } catch { + if (getRuntimeKey() !== submitRuntimeKey) return; + toast.error(t('chat.chatInput.toast.attachNamedFailed', { name: mention.filename })); + return; + } + } + } + // Inline review comments and synthetic context are consumed before // assembly so a failed send can restore exactly what it took. const syntheticParts = consumePendingSyntheticParts(); @@ -1079,7 +1123,7 @@ const ChatInputComponent: React.FC = ({ onOpenSettings, scrollTo return { text: sanitizedText, agentName: mention?.name }; }, extractFileMentions: (text) => { - const { sanitizedText, attachments } = extractInlineFileMentions(text); + const { sanitizedText, attachments } = extractInlineFileMentions(text, preparedDocumentMentions); return { text: sanitizedText, attachments }; }, sanitizeAttachments: sanitizeAttachmentsForSend, diff --git a/packages/ui/src/components/chat/MarkdownImageGallery.tsx b/packages/ui/src/components/chat/MarkdownImageGallery.tsx index faffc569..d4b27341 100644 --- a/packages/ui/src/components/chat/MarkdownImageGallery.tsx +++ b/packages/ui/src/components/chat/MarkdownImageGallery.tsx @@ -1,25 +1,92 @@ import React from 'react'; +import { toast } from 'sonner'; import { Icon } from '@/components/icon/Icon'; import { useEffectiveDirectory } from '@/hooks/useEffectiveDirectory'; +import { useI18n } from '@/lib/i18n'; +import { + acquireRuntimeUrlAuthToken, + refreshRuntimeUrlAuthToken, + subscribeRuntimeUrlAuthToken, +} from '@/lib/runtime-auth'; +import { getRuntimeApiBaseUrl } from '@/lib/runtime-switch'; +import { isVSCodeRuntime } from '@/lib/desktop'; import type { ToolPopupContent } from './message/types'; import { extractMarkdownImageCandidates, MAX_MARKDOWN_IMAGE_COUNT, type MarkdownImageCandidate, } from './markdown/markdownCore'; -import { resolveMarkdownImageSource } from './markdown/markdownImageAssets'; +import { + getPreparedMarkdownImageUrl, + isLocalMarkdownImageSource, + prepareLocalMarkdownImages, + resolveMarkdownImageSource, + resolveWorkspaceMarkdownImageSource, + type PreparedMarkdownImage, +} from './markdown/markdownImageAssets'; + +const useAssetAuth = (enabled: boolean): { ready: boolean; nonce: number } => { + const [ready, setReady] = React.useState(false); + const [nonce, setNonce] = React.useState(0); + const apiBaseUrl = getRuntimeApiBaseUrl(); + + React.useEffect(() => { + if (!enabled) { + setReady(false); + return; + } + let cancelled = false; + let retryTimer: ReturnType | undefined; + const release = acquireRuntimeUrlAuthToken(apiBaseUrl); + const unsubscribe = subscribeRuntimeUrlAuthToken(() => { + if (!cancelled) setNonce((current) => current + 1); + }); + const refresh = () => { + void refreshRuntimeUrlAuthToken(apiBaseUrl) + .then(() => { + if (!cancelled) setReady(true); + }) + .catch(() => { + if (!cancelled) retryTimer = setTimeout(refresh, 1000); + }); + }; + refresh(); + return () => { + cancelled = true; + if (retryTimer) clearTimeout(retryTimer); + release(); + unsubscribe(); + }; + }, [apiBaseUrl, enabled]); + + return { ready: !enabled || ready, nonce }; +}; const MarkdownImageThumbnail: React.FC<{ candidate: MarkdownImageCandidate; + preparation?: PreparedMarkdownImage; directory: string; + assetAuthReady: boolean; + assetAuthNonce: number; + useWorkspaceFsBridge: boolean; onShowPopup?: (content: ToolPopupContent) => void; -}> = ({ candidate, directory, onShowPopup }) => { +}> = ({ + candidate, + preparation, + directory, + assetAuthReady, + assetAuthNonce, + useWorkspaceFsBridge, + onShowPopup, +}) => { + const { t } = useI18n(); const thumbnailRef = React.useRef(null); const [shouldLoad, setShouldLoad] = React.useState(false); - const [image, setImage] = React.useState<{ - url: string; - status: 'loading' | 'ready' | 'error'; - }>({ url: '', status: 'loading' }); + const [image, setImage] = React.useState<{ url: string; status: 'loading' | 'ready' | 'error' }>({ + url: '', + status: 'loading', + }); + const local = isLocalMarkdownImageSource(candidate.source); React.useEffect(() => { const thumbnail = thumbnailRef.current; @@ -28,7 +95,6 @@ const MarkdownImageThumbnail: React.FC<{ setShouldLoad(true); return; } - const observer = new IntersectionObserver((entries) => { if (!entries.some((entry) => entry.isIntersecting)) return; setShouldLoad(true); @@ -39,20 +105,45 @@ const MarkdownImageThumbnail: React.FC<{ }, [shouldLoad]); React.useEffect(() => { - if (!shouldLoad) return; + if (!shouldLoad || (local && !useWorkspaceFsBridge && !preparation)) return; + if (local && useWorkspaceFsBridge) { + const controller = new AbortController(); + setImage({ url: '', status: 'loading' }); + void resolveWorkspaceMarkdownImageSource(candidate.source, directory, controller.signal).then((url) => { + if (controller.signal.aborted) return; + setImage({ url, status: 'loading' }); + }).catch(() => { + if (controller.signal.aborted) return; + setImage({ url: '', status: 'error' }); + }); + return () => controller.abort(); + } + if (local) { + if (preparation?.status !== 'ready') { + setImage({ url: '', status: 'error' }); + return; + } + if (!assetAuthReady) return; + setImage({ url: getPreparedMarkdownImageUrl(preparation, directory), status: 'loading' }); + return; + } const controller = new AbortController(); setImage({ url: '', status: 'loading' }); - void resolveMarkdownImageSource(candidate.source, directory, controller.signal) - .then((url) => { - if (!controller.signal.aborted) setImage({ url, status: 'loading' }); - }) - .catch(() => { - if (!controller.signal.aborted) setImage({ url: '', status: 'error' }); - }); + void resolveMarkdownImageSource(candidate.source, controller.signal).then((url) => { + if (controller.signal.aborted) return; + setImage({ url, status: 'loading' }); + }).catch(() => { + if (controller.signal.aborted) return; + setImage({ url: '', status: 'error' }); + }); return () => controller.abort(); - }, [candidate.source, directory, shouldLoad]); + }, [assetAuthNonce, assetAuthReady, candidate.source, directory, local, preparation, shouldLoad, useWorkspaceFsBridge]); const openPreview = React.useCallback(() => { + if (image.status === 'error') { + toast.error(t('filesView.error.previewUnavailable')); + return; + } if (image.status !== 'ready' || !onShowPopup) return; onShowPopup({ open: true, @@ -61,7 +152,7 @@ const MarkdownImageThumbnail: React.FC<{ metadata: { tool: 'markdown-image-preview', filename: candidate.filename }, image: { url: image.url, filename: candidate.filename }, }); - }, [candidate.filename, image, onShowPopup]); + }, [candidate.filename, image, onShowPopup, t]); return ( + )} + label={note.body.trim().split('\n')[0] || note.body.trim()} + value={{t('chat.workStatus.breakdown.pinnedNote')}} + /> + ))} + {visibleKnowledge.plans.map((plan) => ( + { + event.stopPropagation(); + unpinPlan(plan.id); + }} + className="shrink-0 rounded p-0.5 transition-opacity hover:opacity-70 disabled:opacity-40" + > + + + )} + label={plan.title} + value={{t('chat.workStatus.breakdown.pinnedPlan')}} + /> + ))} + {memoryCount > 0 ? ( + {memoryCount}} + /> + ) : null} + = ({ directory }) => { > {mcpServers.map(([name, entry]) => { const connected = entry?.status === 'connected'; + const busy = busyServer === name; const needsAuth = entry?.status === 'needs_auth' || entry?.status === 'needs_client_registration'; const failed = entry?.status === 'failed'; return ( @@ -105,8 +106,9 @@ export const WorkStatusMcpSection: React.FC = ({ directory }) => { leading={( { void handleToggle(name, checked); }} /> @@ -118,7 +120,7 @@ export const WorkStatusMcpSection: React.FC = ({ directory }) => { value={needsAuth ? ( { void handleAuthorize(name); }} > {t('chat.workStatus.mcp.needsAuth')} @@ -126,7 +128,7 @@ export const WorkStatusMcpSection: React.FC = ({ directory }) => { ) : failed ? ( { void handleToggle(name, true); }} > {t('chat.workStatus.mcp.failed')} diff --git a/packages/ui/src/components/chat/work-status/WorkStatusPrimaryGroup.tsx b/packages/ui/src/components/chat/work-status/WorkStatusPrimaryGroup.tsx index a5f12e15..4db88c6c 100644 --- a/packages/ui/src/components/chat/work-status/WorkStatusPrimaryGroup.tsx +++ b/packages/ui/src/components/chat/work-status/WorkStatusPrimaryGroup.tsx @@ -3,7 +3,7 @@ import { useI18n } from '@/lib/i18n'; import { useGitStore } from '@/stores/useGitStore'; import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; import { runBackgroundNetworkTask } from '@/lib/background-network'; -import { getGitHubPrStatusKey, usePrVisualSummary } from '@/stores/useGitHubPrStatusStore'; +import { useFreshestPrVisualSummaryForBranch } from '@/stores/useGitHubPrStatusStore'; import { useSession, useSessionMessages } from '@/sync/sync-context'; import { useConfigStore } from '@/stores/useConfigStore'; import { useUIStore } from '@/stores/useUIStore'; @@ -107,11 +107,7 @@ export const WorkStatusPrimaryGroup: React.FC = ({ sessionId, directory, // Read-only: PR watching is owned by the background tracker. Starting a watch // here would multiply GitHub requests per open session, which is exactly the // fan-out the PR-status concurrency gate exists to prevent. - const prKey = React.useMemo( - () => (directory && branch ? getGitHubPrStatusKey(directory, branch) : null), - [directory, branch], - ); - const prSummary = usePrVisualSummary(prKey); + const prSummary = useFreshestPrVisualSummaryForBranch(directory, branch); // `getCurrentModel` is an imperative getter: its reference never changes, so // calling it in render subscribes to nothing. Subscribe to the selected model diff --git a/packages/ui/src/components/chat/work-status/WorkStatusPrimitives.tsx b/packages/ui/src/components/chat/work-status/WorkStatusPrimitives.tsx index 4ef98696..626bb0c4 100644 --- a/packages/ui/src/components/chat/work-status/WorkStatusPrimitives.tsx +++ b/packages/ui/src/components/chat/work-status/WorkStatusPrimitives.tsx @@ -25,7 +25,7 @@ const SECTION_CLASS = cn( '[&:not(:first-child)]:border-[var(--interactive-border)] [&:not(:first-child)]:pt-3', ); -const HEADING_CLASS = 'text-xs font-normal text-muted-foreground'; +const HEADING_CLASS = 'text-xs font-semibold text-foreground'; export const WorkStatusSection: React.FC<{ title: string; @@ -158,7 +158,10 @@ export const WorkStatusRow: React.FC = ({ ); - const shared = cn('flex h-7 w-full items-center gap-2 rounded-md px-1 text-left', className); + const shared = cn( + 'flex h-7 w-full items-center gap-2 rounded-md px-1 text-left text-muted-foreground', + className, + ); if (!onClick) return
{body}
; diff --git a/packages/ui/src/components/chat/work-status/WorkStatusUsageSection.tsx b/packages/ui/src/components/chat/work-status/WorkStatusUsageSection.tsx index e26f55e1..3484512e 100644 --- a/packages/ui/src/components/chat/work-status/WorkStatusUsageSection.tsx +++ b/packages/ui/src/components/chat/work-status/WorkStatusUsageSection.tsx @@ -124,8 +124,7 @@ export const WorkStatusUsageSection: React.FC = () => { } - label={group.providerName} - muted + label={{group.providerName}} value={group.status && group.rows.length === 0 ? ( {group.status} ) : undefined} diff --git a/packages/ui/src/components/chat/work-status/contextUsage.test.ts b/packages/ui/src/components/chat/work-status/contextUsage.test.ts index c2e0a6e4..34f538f6 100644 --- a/packages/ui/src/components/chat/work-status/contextUsage.test.ts +++ b/packages/ui/src/components/chat/work-status/contextUsage.test.ts @@ -14,8 +14,8 @@ describe('computeContextUsage', () => { }); test('reports the latest turn rather than a sum across turns', () => { - // Each assistant turn reports the whole window it saw, so adding them up - // would report several times the real fill. + // A turn's tokens describe that turn's window, so adding turns up would + // report several times the real fill. const usage = computeContextUsage( [ assistant({ input: 400, output: 0, reasoning: 0 }, 'old'), @@ -61,4 +61,24 @@ describe('computeContextUsage', () => { const usage = computeContextUsage([assistant({ input: 10 })], 100); expect(usage?.totalTokens).toBe(10); }); + + test('prefers the server-reported total over summing round-trip fields', () => { + // Real payload from opencode 1.18.18: ~14 tool-call round-trips accumulated + // cache.read to 3.29M while the 1M window really held 232,872. Summing + // rendered 330.6%; the reported total renders the real 23.3%. + const usage = computeContextUsage( + [assistant({ total: 232_872, input: 0, output: 14_523, reasoning: 0, cache: { read: 3_291_956, write: 0 } })], + 1_000_000, + ); + expect(usage?.totalTokens).toBe(232_872); + expect(usage?.percent.toFixed(4)).toBe('23.2872'); + }); + + test('selects a message whose only signal is the reported total', () => { + const usage = computeContextUsage( + [assistant({ total: 5_000, input: 0, output: 0, reasoning: 0 })], + 100_000, + ); + expect(usage?.totalTokens).toBe(5_000); + }); }); diff --git a/packages/ui/src/components/chat/work-status/contextUsage.ts b/packages/ui/src/components/chat/work-status/contextUsage.ts index c30d57f6..920d6963 100644 --- a/packages/ui/src/components/chat/work-status/contextUsage.ts +++ b/packages/ui/src/components/chat/work-status/contextUsage.ts @@ -13,7 +13,11 @@ * global read to race with. */ +import { contextTokensFromBreakdown } from '@/stores/utils/tokenUtils'; + type MessageTokens = { + /** Server-reported window of the turn's final round-trip; absent on older servers. */ + total?: number; input?: number; output?: number; reasoning?: number; @@ -37,18 +41,12 @@ type WorkStatusContextUsage = { /** The store's own fallback when a model exposes no context limit. */ export const DEFAULT_CONTEXT_LIMIT = 200_000; -const sumTokens = (tokens: MessageTokens): number => ( - (tokens.input ?? 0) - + (tokens.output ?? 0) - + (tokens.reasoning ?? 0) - + (tokens.cache?.read ?? 0) - + (tokens.cache?.write ?? 0) -); - /** * Usage from the newest assistant message that reported a non-zero token count. - * Each assistant turn reports the whole window it saw, so the latest one is the - * current fill — not a sum across turns. + * The latest turn describes the current fill — not a sum across turns. Within + * a turn, the server-reported `total` is the final round-trip's window; + * summing the breakdown fields instead overstates multi-step turns, whose + * input/cache fields accumulate across round-trips. */ export const computeContextUsage = ( messages: readonly MessageLike[], @@ -60,7 +58,7 @@ export const computeContextUsage = ( const message = messages[index]; if (message?.role !== 'assistant' || !message.tokens) continue; - const totalTokens = sumTokens(message.tokens); + const totalTokens = contextTokensFromBreakdown(message.tokens); if (totalTokens <= 0) continue; const limit = contextLimit > 0 ? contextLimit : DEFAULT_CONTEXT_LIMIT; diff --git a/packages/ui/src/components/chat/work-status/draftKnowledge.test.ts b/packages/ui/src/components/chat/work-status/draftKnowledge.test.ts new file mode 100644 index 00000000..e4333f63 --- /dev/null +++ b/packages/ui/src/components/chat/work-status/draftKnowledge.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'bun:test'; + +import { resolveDraftPinnedKnowledge } from './draftKnowledge'; + +describe('resolveDraftPinnedKnowledge', () => { + test('shows only notes and plans pinned on this draft', () => { + expect(resolveDraftPinnedKnowledge( + [{ id: 'note-a', body: 'Attached' }, { id: 'note-b', body: 'Not attached' }], + [{ id: 'plan-a', title: 'Attached plan' }, { id: 'plan-b', title: 'Other plan' }], + { notes: ['note-a'], plans: ['plan-a'] }, + )).toEqual({ + notes: [{ id: 'note-a', body: 'Attached' }], + plans: [{ id: 'plan-a', title: 'Attached plan' }], + }); + }); + + test('drops stale ids without borrowing project-wide pins', () => { + expect(resolveDraftPinnedKnowledge( + [{ id: 'note-a', body: 'Project note' }], + [{ id: 'plan-a', title: 'Project plan' }], + { notes: ['missing'], plans: [] }, + )).toEqual({ notes: [], plans: [] }); + }); +}); diff --git a/packages/ui/src/components/chat/work-status/draftKnowledge.ts b/packages/ui/src/components/chat/work-status/draftKnowledge.ts new file mode 100644 index 00000000..731af293 --- /dev/null +++ b/packages/ui/src/components/chat/work-status/draftKnowledge.ts @@ -0,0 +1,17 @@ +import type { SessionKnowledgeSummary, SessionProjectContextPins } from '@/lib/sessionKnowledgeApi'; + +type NoteSource = { id: string; body: string }; +type PlanSource = { id: string; title: string }; + +export const resolveDraftPinnedKnowledge = ( + notes: NoteSource[], + plans: PlanSource[], + pins: SessionProjectContextPins, +): Pick => { + const noteIds = new Set(pins.notes); + const planIds = new Set(pins.plans); + return { + notes: notes.filter((note) => noteIds.has(note.id)).map(({ id, body }) => ({ id, body })), + plans: plans.filter((plan) => planIds.has(plan.id)).map(({ id, title }) => ({ id, title })), + }; +}; diff --git a/packages/ui/src/components/chat/work-status/usageHeadline.test.ts b/packages/ui/src/components/chat/work-status/usageHeadline.test.ts index 998808a0..64b66292 100644 --- a/packages/ui/src/components/chat/work-status/usageHeadline.test.ts +++ b/packages/ui/src/components/chat/work-status/usageHeadline.test.ts @@ -36,6 +36,10 @@ describe('resolveQuotaProviderId', () => { expect(resolveQuotaProviderId('anthropic')).toBe('claude'); }); + test('maps the opencode-claude integration provider onto Claude quota', () => { + expect(resolveQuotaProviderId('claude-code')).toBe('claude'); + }); + test('is case and whitespace tolerant, and rejects empties', () => { expect(resolveQuotaProviderId(' OpenAI ')).toBe('codex'); expect(resolveQuotaProviderId('')).toBeNull(); diff --git a/packages/ui/src/components/chat/work-status/usageHeadline.ts b/packages/ui/src/components/chat/work-status/usageHeadline.ts index ad80e553..502a1bc3 100644 --- a/packages/ui/src/components/chat/work-status/usageHeadline.ts +++ b/packages/ui/src/components/chat/work-status/usageHeadline.ts @@ -13,11 +13,15 @@ import type { UsageProviderGroup, UsageLimitRow } from '@/components/usage/usage /** * Quota provider ids mostly match OpenCode provider ids; these are the ones * that do not. Unmatched providers simply produce no headline. + * + * `claude-code` is the provider the opencode-claude integration registers, and + * it bills against the same Claude subscription the `claude` quota reports. */ const QUOTA_PROVIDER_ALIASES = new Map([ ['openai', 'codex'], ['chatgpt', 'codex'], ['anthropic', 'claude'], + ['claude-code', 'claude'], ['gemini', 'google'], ]); diff --git a/packages/ui/src/components/icon/Icon.tsx b/packages/ui/src/components/icon/Icon.tsx index 3956cfba..be6077de 100644 --- a/packages/ui/src/components/icon/Icon.tsx +++ b/packages/ui/src/components/icon/Icon.tsx @@ -30,6 +30,29 @@ function ensureSpriteOnce() { spriteInjected = true } +/** + * Append a single missing symbol. Needed when the sprite was injected before a + * newly generated icon landed (HMR / late sprite regenerate) — a one-shot inject + * would otherwise leave `` pointing at nothing. + */ +function ensureSpriteSymbol(name: IconName) { + if (typeof document === "undefined") return + ensureSpriteOnce() + if (document.getElementById(`oc-${name}`)) return + + const content = iconSpriteData[name] + if (typeof content !== "string") return + + const sprite = document.getElementById(SPRITE_ID) + if (!sprite) return + + const symbol = document.createElementNS("http://www.w3.org/2000/svg", "symbol") + symbol.id = `oc-${name}` + symbol.setAttribute("viewBox", "0 0 24 24") + symbol.innerHTML = content + sprite.appendChild(symbol) +} + export interface IconProps extends React.ComponentPropsWithoutRef<"svg"> { name: IconName } @@ -38,7 +61,7 @@ export const Icon = React.memo(({ name, className, ...rest }: IconProps) => { // Inline sprite injection during render – must run before tries // to resolve the #oc-* reference during the same commit. if (typeof document !== "undefined") { - ensureSpriteOnce() + ensureSpriteSymbol(name) } return ( diff --git a/packages/ui/src/components/icon/sprite.ts b/packages/ui/src/components/icon/sprite.ts index 769b58cd..d6da37c9 100644 --- a/packages/ui/src/components/icon/sprite.ts +++ b/packages/ui/src/components/icon/sprite.ts @@ -28,10 +28,12 @@ export const iconSpriteData = { "bar-chart-2": ``, "bar-chart-box": ``, "book": ``, + "book-marked": ``, "book-open": ``, "booklet": ``, "braces": ``, "brain": ``, + "brain-4": ``, "brain-ai-3": ``, "briefcase": ``, "bug": ``, @@ -51,6 +53,7 @@ export const iconSpriteData = { "checkbox-blank-circle-fill": ``, "checkbox-circle": ``, "checkbox-multiple": ``, + "claude-code": ``, "clipboard": ``, "close": ``, "close-circle": ``, @@ -62,11 +65,12 @@ export const iconSpriteData = { "code-sslash": ``, "collapse-vertical": ``, "command": ``, + "command-code": ``, "compass-3": ``, "computer": ``, "contract-up-down": ``, "corner-down-left": ``, - "cursor": ``, + "cursor": ``, "database-2": ``, "delete-bin": ``, "discord-fill": ``, @@ -159,6 +163,7 @@ export const iconSpriteData = { "lock-unlock": ``, "loop-right-ai": ``, "macbook": ``, + "markup": ``, "menu-2": ``, "menu-fold-2": ``, "menu-search": ``, @@ -225,6 +230,7 @@ export const iconSpriteData = { "target": ``, "target-fill": ``, "task": ``, + "telegram-fill": ``, "terminal": ``, "terminal-box": ``, "terminal-window": ``, diff --git a/packages/ui/src/components/layout/ContextPanel.tsx b/packages/ui/src/components/layout/ContextPanel.tsx index 5abd20be..8c24e134 100644 --- a/packages/ui/src/components/layout/ContextPanel.tsx +++ b/packages/ui/src/components/layout/ContextPanel.tsx @@ -38,6 +38,8 @@ import { Icon } from "@/components/icon/Icon"; import { EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST, EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE, + EMBEDDED_VISIBILITY_REQUEST, + EMBEDDED_VISIBILITY_UPDATE, getActiveEmbeddedSessionChatTab, getOrCreateEmbeddedSessionChatURL, type EmbeddedSessionChatURLCacheEntry, @@ -803,27 +805,34 @@ export const ContextPanel: React.FC = () => { } }, [allowPromptingSubagentSessions]); + const postEmbeddedVisibilityToChat = React.useCallback(( + tabID: string, + frame: HTMLIFrameElement, + targetOrigin: string, + ) => { + const frameWindow = frame.contentWindow; + if (!frameWindow) { + return; + } + + frameWindow.postMessage( + { + type: EMBEDDED_VISIBILITY_UPDATE, + payload: { visible: activeChatTabID === tabID }, + }, + targetOrigin, + ); + }, [activeChatTabID]); + const postEmbeddedVisibilityToChats = React.useCallback(() => { if (typeof window === 'undefined') { return; } for (const [tabID, frame] of chatFrameRefs.current.entries()) { - const frameWindow = frame.contentWindow; - if (!frameWindow) { - continue; - } - - const payload = { visible: activeChatTabID === tabID }; - frameWindow.postMessage( - { - type: 'openchamber:embedded-visibility', - payload, - }, - window.location.origin, - ); + postEmbeddedVisibilityToChat(tabID, frame, window.location.origin); } - }, [activeChatTabID]); + }, [postEmbeddedVisibilityToChat]); React.useEffect(() => { if (typeof window === 'undefined') { @@ -835,13 +844,18 @@ export const ContextPanel: React.FC = () => { return; } - const isKnownChatFrame = Array.from(chatFrameRefs.current.values()) - .some((frame) => frame.contentWindow === event.source); - if (!isKnownChatFrame) { + const sourceChatFrame = Array.from(chatFrameRefs.current.entries()) + .find(([, frame]) => frame.contentWindow === event.source); + if (!sourceChatFrame) { return; } const data = event.data as { type?: unknown; requestId?: unknown }; + if (data?.type === EMBEDDED_VISIBILITY_REQUEST) { + const [tabID, frame] = sourceChatFrame; + postEmbeddedVisibilityToChat(tabID, frame, event.origin); + return; + } if (data?.type === EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST) { if (typeof data.requestId !== 'string' || !data.requestId) return; const runtimeKey = getRuntimeKey(); @@ -882,7 +896,7 @@ export const ContextPanel: React.FC = () => { window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); - }, [postChatSettingsSyncToEmbeddedChat, postThemeSyncToEmbeddedChat, setThemeMode, themeMode]); + }, [postChatSettingsSyncToEmbeddedChat, postEmbeddedVisibilityToChat, postThemeSyncToEmbeddedChat, setThemeMode, themeMode]); React.useLayoutEffect(() => { const hasAnyChatTab = tabs.some((tab) => tab.mode === 'chat'); @@ -926,7 +940,7 @@ export const ContextPanel: React.FC = () => { : activeTab?.mode === 'notes' ? : activeTab?.mode === 'plan' - ? + ? : null; const browserTabs = React.useMemo( diff --git a/packages/ui/src/components/layout/ContextSidebarTab.tsx b/packages/ui/src/components/layout/ContextSidebarTab.tsx index 1e08bd0b..d6f5d549 100644 --- a/packages/ui/src/components/layout/ContextSidebarTab.tsx +++ b/packages/ui/src/components/layout/ContextSidebarTab.tsx @@ -11,6 +11,7 @@ import { computeCacheHitRate } from '@/stores/utils/tokenUtils'; import { useSessions, useSessionMessageRecords } from '@/sync/sync-context'; import { copyTextToClipboard } from '@/lib/clipboard'; import { getCurrentIntlLocale, useI18n } from '@/lib/i18n'; +import { formatMoney } from '@/lib/money'; import { derivePartsLabel, deriveUserSnippet, @@ -92,6 +93,7 @@ const extractTokenBreakdown = (message: SessionMessage): TokenBreakdown => { } const breakdown = source as { + total?: unknown; input?: unknown; output?: unknown; reasoning?: unknown; @@ -103,6 +105,10 @@ const extractTokenBreakdown = (message: SessionMessage): TokenBreakdown => { const reasoning = toNonNegativeNumber(breakdown.reasoning); const cacheRead = toNonNegativeNumber(breakdown.cache?.read); const cacheWrite = toNonNegativeNumber(breakdown.cache?.write); + // Multi-step turns accumulate the fields across API round-trips (every tool + // call re-reads the whole cached prompt), so summing them overstates the + // window. The server-reported total is the final round-trip's window. + const reportedTotal = toNonNegativeNumber(breakdown.total); return { input, @@ -110,7 +116,7 @@ const extractTokenBreakdown = (message: SessionMessage): TokenBreakdown => { reasoning, cacheRead, cacheWrite, - total: input + output + reasoning + cacheRead + cacheWrite, + total: reportedTotal > 0 ? reportedTotal : input + output + reasoning + cacheRead + cacheWrite, }; }; @@ -231,16 +237,6 @@ const computeContextBreakdown = ( const formatNumber = (value: number): string => value.toLocaleString(getCurrentIntlLocale()); -const formatMoney = (value: number): string => { - if (!Number.isFinite(value) || value <= 0) return new Intl.NumberFormat(getCurrentIntlLocale(), { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(0); - return new Intl.NumberFormat(getCurrentIntlLocale(), { - style: 'currency', - currency: 'USD', - minimumFractionDigits: value < 0.01 ? 4 : 2, - maximumFractionDigits: value < 0.01 ? 4 : 2, - }).format(value); -}; - const formatDateTime = (timestamp: number | null, timeFormatPreference: TimeFormatPreference): string => { if (!timestamp || !Number.isFinite(timestamp)) return '-'; return formatDateTimeForPreference(timestamp, timeFormatPreference, { diff --git a/packages/ui/src/components/layout/RightSidebarTabs.tsx b/packages/ui/src/components/layout/RightSidebarTabs.tsx index dbfb46f4..cd8b2f1e 100644 --- a/packages/ui/src/components/layout/RightSidebarTabs.tsx +++ b/packages/ui/src/components/layout/RightSidebarTabs.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { ProjectNotesTodoPanel } from '@/components/session/ProjectNotesTodoPanel'; +import { ProjectNotesTodoPanel } from '@/components/session/project-context/ProjectNotesTodoPanel'; import { useGitStore } from '@/stores/useGitStore'; import { useProjectsStore } from '@/stores/useProjectsStore'; import { useDirectoryStore } from '@/stores/useDirectoryStore'; @@ -8,7 +8,7 @@ import { formatDirectoryName } from '@/lib/utils'; export const ProjectContextPanel: React.FC<{ onActionComplete?: () => void; - onOpenPlan?: (plan: { path: string; title: string }) => void; + onOpenPlan?: (plan: { id: string; title: string }) => void; }> = ({ onActionComplete, onOpenPlan }) => { const activeProjectId = useProjectsStore((state) => state.activeProjectId); const projects = useProjectsStore((state) => state.projects); @@ -49,7 +49,8 @@ export const ProjectContextPanel: React.FC<{ }, [activeProject, gitDirectories]); return ( -
+ /* The panel scrolls its own tab content; a scroller here would nest. */ +
( + Array.from(dataTransfer.types).includes('Files') +); + +const getExternalFiles = (dataTransfer: DataTransfer): File[] => { + const items = Array.from(dataTransfer.items); + if (items.length === 0) return Array.from(dataTransfer.files); + + return items.flatMap((item) => { + if (item.kind !== 'file' || item.webkitGetAsEntry()?.isDirectory) return []; + const file = item.getAsFile(); + return file ? [file] : []; + }); +}; + +const getUploadName = (file: File): string | null => { + const name = file.name; + if (!name || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) { + return null; + } + return name; +}; + const sortNodes = (items: FileNode[]) => items.slice().sort((a, b) => { if (a.type !== b.type) { @@ -93,6 +129,22 @@ const getRelativePath = (root: string, path: string): string => { return normalizedPath.slice(normalizedRoot.length + 1); }; +const getDropTargetLabel = (root: string, target: string): string => { + const relativePath = getRelativePath(root, target); + if (relativePath !== '.') return relativePath; + + const normalizedRoot = normalizePath(root); + return normalizedRoot.split('/').filter(Boolean).pop() ?? normalizedRoot; +}; + +const getParentPath = (value: string): string => { + const normalized = normalizePath(value); + const separatorIndex = normalized.lastIndexOf('/'); + if (separatorIndex < 0) return ''; + if (separatorIndex === 0) return '/'; + return normalized.slice(0, separatorIndex); +}; + const isAbsolutePath = (value: string): boolean => { return value.startsWith('/') || value.startsWith('//') || /^[A-Za-z]:\//.test(value); }; @@ -194,6 +246,8 @@ interface FileRowProps { isBrowserClient: boolean; status?: FileStatus | null; badge?: { modified: number; added: number } | null; + isDropTarget: boolean; + canUpload: boolean; permissions: { canRename: boolean; canCreateFile: boolean; @@ -206,6 +260,8 @@ interface FileRowProps { onToggle: (path: string) => void; onRevealPath: (path: string) => void; onOpenDialog: (type: 'createFile' | 'createFolder' | 'rename' | 'delete', data: { path: string; name?: string; type?: 'file' | 'directory' }) => void; + onSetDropTarget: (path: string | null) => void; + onDropFiles: (directory: string, dataTransfer: DataTransfer) => void; } const FileRow: React.FC = ({ @@ -216,15 +272,20 @@ const FileRow: React.FC = ({ isBrowserClient, status, badge, + isDropTarget, + canUpload, permissions, downloadFile, onSelect, onToggle, onRevealPath, onOpenDialog, + onSetDropTarget, + onDropFiles, }) => { const { t } = useI18n(); const isDir = node.type === 'directory'; + const uploadDirectory = isDir ? node.path : getParentPath(node.path); const { canRename, canCreateFile, canCreateFolder, canDelete, canReveal } = permissions; const canDownload = !isDir && Boolean(downloadFile); const canRevealPath = canReveal && !isBrowserClient; @@ -333,9 +394,40 @@ const FileRow: React.FC = ({ e.dataTransfer.effectAllowed = 'copy'; }, [node.path, root]); + const handleExternalDragOver = React.useCallback((event: React.DragEvent) => { + if (!canUpload || !uploadDirectory || !hasExternalFiles(event.dataTransfer)) return; + event.preventDefault(); + event.stopPropagation(); + event.dataTransfer.dropEffect = 'copy'; + onSetDropTarget(uploadDirectory); + }, [canUpload, onSetDropTarget, uploadDirectory]); + + const handleExternalDragLeave = React.useCallback((event: React.DragEvent) => { + if (!canUpload || !uploadDirectory || !hasExternalFiles(event.dataTransfer)) return; + if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return; + event.stopPropagation(); + onSetDropTarget(null); + }, [canUpload, onSetDropTarget, uploadDirectory]); + + const handleExternalDrop = React.useCallback((event: React.DragEvent) => { + if (!canUpload || !uploadDirectory || !hasExternalFiles(event.dataTransfer)) return; + event.preventDefault(); + event.stopPropagation(); + onDropFiles(uploadDirectory, event.dataTransfer); + }, [canUpload, onDropFiles, uploadDirectory]); + return ( - }> + + )}>
- +
+
    {searching ? (
  • @@ -1235,7 +1459,52 @@ export const SidebarFilesTree: React.FC = () => {
  • {t('sidebarFilesTree.state.loading')}
  • )}
-
+ + {dropTarget ? ( +
+ + + {t(isUploading ? 'sidebarFilesTree.drop.uploading' : 'sidebarFilesTree.drop.target', { path: dropTargetLabel })} + +
+ ) : null} +
+ + !open && setUploadConflicts(null)}> + + + {t('sidebarFilesTree.dialog.uploadConflicts.title')} + + {t('sidebarFilesTree.dialog.uploadConflicts.description', { path: uploadConflicts?.directory ?? '' })} + + + + {uploadConflicts?.files.map((file, index) => ( +
+ {file.name} +
+ ))} +
+ + + + +
+
{/* CRUD dialogs (matching FilesView) */} !open && setActiveDialog(null)}> diff --git a/packages/ui/src/components/layout/VSCodeLayout.tsx b/packages/ui/src/components/layout/VSCodeLayout.tsx index de1f1772..5ccf8a46 100644 --- a/packages/ui/src/components/layout/VSCodeLayout.tsx +++ b/packages/ui/src/components/layout/VSCodeLayout.tsx @@ -5,9 +5,10 @@ import { SessionDialogs } from '@/components/session/SessionDialogs'; import { ChatView } from '@/components/views/ChatView'; import { useSessionUIStore } from '@/sync/session-ui-store'; import { useViewportStore } from '@/sync/viewport-store'; -import { useSessions, useDirectorySync, useSessionMessages, useSessionMessagesResolved } from '@/sync/sync-context'; +import { useSessions, useDirectorySync, useSession, useSessionMessages, useSessionMessagesResolved } from '@/sync/sync-context'; import { useConfigStore } from '@/stores/useConfigStore'; import { resolveGlobalSessionDirectory, useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore'; +import { contextTokensFromBreakdown } from '@/stores/utils/tokenUtils'; import { ContextUsageDisplay } from '@/components/ui/ContextUsageDisplay'; import { McpDropdown } from '@/components/mcp/McpDropdown'; import { ArchiveAllDropdown } from '@/components/session/ArchiveAllDropdown'; @@ -665,6 +666,7 @@ const VSCodeHeader: React.FC = ({ title, showBack, onBack, on const providers = useConfigStore((state) => state.providers); const currentSessionId = useSessionUIStore((state) => state.currentSessionId); const activeProjectId = useProjectsStore((state) => state.activeProjectId); + const currentSession = useSession(currentSessionId ?? ''); const currentSessionMessages = useSessionMessages(currentSessionId ?? ''); const currentSessionMessagesResolved = useSessionMessagesResolved(currentSessionId ?? ''); const quotaResults = useQuotaStore((state) => state.results); @@ -702,7 +704,7 @@ const VSCodeHeader: React.FC = ({ title, showBack, onBack, on } if (!lastTokens && message.tokens) { - const total = message.tokens.input + message.tokens.output + message.tokens.reasoning + (message.tokens.cache?.read ?? 0) + (message.tokens.cache?.write ?? 0); + const total = contextTokensFromBreakdown(message.tokens); if (total > 0) { lastTokens = message.tokens; lastMessageId = (currentSessionMessages[i] as { id?: string }).id; @@ -730,7 +732,7 @@ const VSCodeHeader: React.FC = ({ title, showBack, onBack, on } const lastTokens = headerMessageSummary.lastTokens; - const totalTokens = lastTokens.input + lastTokens.output + lastTokens.reasoning + (lastTokens.cache?.read ?? 0) + (lastTokens.cache?.write ?? 0); + const totalTokens = contextTokensFromBreakdown(lastTokens); const thresholdLimit = contextLimit > 0 ? contextLimit : 200000; const percentage = contextLimit > 0 ? Math.round((totalTokens / contextLimit) * 100) : 0; const normalizedOutput = outputLimit > 0 ? Math.round((lastTokens.output / outputLimit) * 100) : undefined; @@ -1021,6 +1023,7 @@ const VSCodeHeader: React.FC = ({ title, showBack, onBack, on percentage={stableContextUsage.percentage} contextLimit={stableContextUsage.contextLimit} outputLimit={stableContextUsage.outputLimit ?? 0} + cost={(currentSession?.cost ?? 0) > 0 ? currentSession?.cost : null} className="h-9 shrink-0 pl-1 pr-1 typography-ui-label" valueClassName="font-semibold leading-none" hideIcon diff --git a/packages/ui/src/components/layout/__tests__/issue-2815-sessionChatIframesMountAllTabs.test.ts b/packages/ui/src/components/layout/__tests__/issue-2815-sessionChatIframesMountAllTabs.test.ts index d540f359..619a8cd2 100644 --- a/packages/ui/src/components/layout/__tests__/issue-2815-sessionChatIframesMountAllTabs.test.ts +++ b/packages/ui/src/components/layout/__tests__/issue-2815-sessionChatIframesMountAllTabs.test.ts @@ -19,6 +19,7 @@ import { } from '../contextPanelEmbeddedChat'; const __dirname = dirname(fileURLToPath(import.meta.url)); +const appSource = readFileSync(join(__dirname, '..', '..', '..', 'App.tsx'), 'utf-8'); const contextPanelSource = readFileSync(join(__dirname, '..', 'ContextPanel.tsx'), 'utf-8'); type FixtureTab = { @@ -117,6 +118,7 @@ describe('issue #2815 active-only chat iframe source guard', () => { expect(block).toContain(' { "const activeChatSessionID = isOpen && activeTab?.mode === 'chat'", ); }); + + test('answers the mounted iframe visibility handshake from the active tab', () => { + expect(contextPanelSource).toContain('data?.type === EMBEDDED_VISIBILITY_REQUEST'); + expect(contextPanelSource).toContain('frame.contentWindow === event.source'); + expect(contextPanelSource).toContain('payload: { visible: activeChatTabID === tabID }'); + }); + + test('requests authoritative visibility after installing the iframe listener', () => { + const effectStart = appSource.indexOf('const applyVisibility = (payload?: EmbeddedVisibilityPayload) => {'); + const listenerIndex = appSource.indexOf("window.addEventListener('message', handleMessage);", effectStart); + const requestIndex = appSource.indexOf('requestEmbeddedSessionVisibility();', effectStart); + + expect(effectStart).toBeGreaterThan(-1); + expect(listenerIndex).toBeGreaterThan(effectStart); + expect(requestIndex).toBeGreaterThan(listenerIndex); + }); + + test('gates embedded chat background work on visibility but keeps message history enabled', () => { + expect(appSource).toContain( + 'const embeddedBackgroundWorkEnabled = !embeddedSessionChat || isEmbeddedVisible;', + ); + expect(appSource).toContain('active={embeddedBackgroundWorkEnabled}'); + expect(appSource).toContain('messagesEnabled={true}'); + expect(appSource).toContain( + 'useWebNotificationStream({ enabled: embeddedBackgroundWorkEnabled });', + ); + }); }); describe('issue #2815 persisted scenario', () => { diff --git a/packages/ui/src/components/layout/contextPanelEmbeddedChat.test.ts b/packages/ui/src/components/layout/contextPanelEmbeddedChat.test.ts index 1c2cb866..26bdfea1 100644 --- a/packages/ui/src/components/layout/contextPanelEmbeddedChat.test.ts +++ b/packages/ui/src/components/layout/contextPanelEmbeddedChat.test.ts @@ -5,11 +5,13 @@ import { buildEmbeddedSessionChatURL, EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST, EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE, + EMBEDDED_VISIBILITY_REQUEST, getOrCreateEmbeddedSessionChatURL, getActiveEmbeddedSessionChatTab, getEmbeddedSessionChatOriginSessionId, isEmbeddedSessionChat, requestEmbeddedSessionRuntimeBootstrap, + requestEmbeddedSessionVisibility, resetEmbeddedSessionChatCache, type EmbeddedSessionChatURLCacheEntry, } from './contextPanelEmbeddedChat'; @@ -171,6 +173,22 @@ describe('active embedded session chat', () => { expect(getActiveEmbeddedSessionChatTab(tabs, null)).toBeNull(); expect(getActiveEmbeddedSessionChatTab(tabs, 'missing-chat')).toBeNull(); }); + + test('requests authoritative visibility from the same-origin parent', () => { + installWindowLocation('http://127.0.0.1:5173/app?ocPanel=session-chat&sessionId=ses_1'); + resetEmbeddedSessionChatCache(); + const calls: Array<{ message: unknown; origin: string }> = []; + (window as unknown as { parent: { postMessage: (message: unknown, origin: string) => void } }).parent = { + postMessage: (message, origin) => calls.push({ message, origin }), + }; + + requestEmbeddedSessionVisibility(); + + expect(calls).toEqual([{ + message: { type: EMBEDDED_VISIBILITY_REQUEST }, + origin: 'http://127.0.0.1:5173', + }]); + }); }); describe('isEmbeddedSessionChat', () => { diff --git a/packages/ui/src/components/layout/contextPanelEmbeddedChat.ts b/packages/ui/src/components/layout/contextPanelEmbeddedChat.ts index 05068ca6..ec1ad921 100644 --- a/packages/ui/src/components/layout/contextPanelEmbeddedChat.ts +++ b/packages/ui/src/components/layout/contextPanelEmbeddedChat.ts @@ -28,6 +28,8 @@ export type EmbeddedSessionRuntimeBootstrap = { export const EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST = 'openchamber:embedded-runtime-bootstrap-request'; export const EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE = 'openchamber:embedded-runtime-bootstrap-response'; +export const EMBEDDED_VISIBILITY_REQUEST = 'openchamber:embedded-visibility-request'; +export const EMBEDDED_VISIBILITY_UPDATE = 'openchamber:embedded-visibility'; const EMBEDDED_RUNTIME_BOOTSTRAP_TIMEOUT_MS = 5_000; const EMBEDDED_RUNTIME_BOOTSTRAP_RETRY_MS = 100; @@ -104,6 +106,13 @@ export const requestEmbeddedSessionRuntimeBootstrap = (): Promise { + if (!isEmbeddedSessionChat() || typeof window === 'undefined' || !window.parent || window.parent === window) { + return; + } + window.parent.postMessage({ type: EMBEDDED_VISIBILITY_REQUEST }, window.location.origin); +}; + const buildEmbeddedSessionChatURLSignature = ( sessionID: string, directory: string | null, diff --git a/packages/ui/src/components/mini-chat/MiniChatLayout.tsx b/packages/ui/src/components/mini-chat/MiniChatLayout.tsx index 4eea6d8f..a32779a1 100644 --- a/packages/ui/src/components/mini-chat/MiniChatLayout.tsx +++ b/packages/ui/src/components/mini-chat/MiniChatLayout.tsx @@ -18,6 +18,7 @@ import { useGitBranchLabel, useGitStore } from '@/stores/useGitStore'; import { useConfigStore } from '@/stores/useConfigStore'; import { Icon } from "@/components/icon/Icon"; import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs'; +import { contextTokensFromBreakdown } from '@/stores/utils/tokenUtils'; import type { SessionContextUsage } from '@/stores/types/sessionTypes'; type MiniChatMode = 'session' | 'draft'; @@ -157,7 +158,7 @@ const MiniChatHeader: React.FC<{ mode: MiniChatMode }> = ({ mode }) => { return null; } - type AssistantTokens = { input: number; output: number; reasoning: number; cache: { read: number; write: number } }; + type AssistantTokens = { total?: number; input: number; output: number; reasoning: number; cache: { read: number; write: number } }; let lastTokens: AssistantTokens | undefined; let lastMessageId: string | undefined; @@ -166,7 +167,7 @@ const MiniChatHeader: React.FC<{ mode: MiniChatMode }> = ({ mode }) => { if (message.role !== 'assistant') continue; const tokens = (message as { tokens?: AssistantTokens }).tokens; if (!tokens) continue; - const total = tokens.input + tokens.output + tokens.reasoning + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0); + const total = contextTokensFromBreakdown(tokens); if (total > 0) { lastTokens = tokens; lastMessageId = message.id; @@ -178,7 +179,7 @@ const MiniChatHeader: React.FC<{ mode: MiniChatMode }> = ({ mode }) => { return null; } - const totalTokens = lastTokens.input + lastTokens.output + lastTokens.reasoning + (lastTokens.cache?.read ?? 0) + (lastTokens.cache?.write ?? 0); + const totalTokens = contextTokensFromBreakdown(lastTokens); const thresholdLimit = contextLimit > 0 ? contextLimit : 200000; const percentage = contextLimit > 0 ? Math.round((totalTokens / contextLimit) * 100) : 0; const normalizedOutput = outputLimit > 0 ? Math.round((lastTokens.output / outputLimit) * 100) : undefined; diff --git a/packages/ui/src/components/sections/integrations/ComingSoonMessengersSection.tsx b/packages/ui/src/components/sections/integrations/ComingSoonMessengersSection.tsx new file mode 100644 index 00000000..ab2693ed --- /dev/null +++ b/packages/ui/src/components/sections/integrations/ComingSoonMessengersSection.tsx @@ -0,0 +1,74 @@ +import React from 'react'; +import { Icon } from '@/components/icon/Icon'; +import { SettingsSection } from '@/components/sections/shared/SettingsSection'; +import type { IconName } from '@/components/icon/icons'; +import { useI18n, type I18nKey } from '@/lib/i18n'; +import { cn } from '@/lib/utils'; + +type ComingSoonMessenger = { + id: 'discord' | 'telegram'; + icon: IconName; + brandClassName: string; + nameKey: I18nKey; + descriptionKey: I18nKey; +}; + +const COMING_SOON_MESSENGERS: readonly ComingSoonMessenger[] = [ + { + id: 'discord', + icon: 'discord-fill', + brandClassName: 'text-[#5865F2]', + nameKey: 'settings.integrations.messengers.discord.name', + descriptionKey: 'settings.integrations.messengers.discord.description', + }, + { + id: 'telegram', + icon: 'telegram-fill', + brandClassName: 'text-[#2AABEE]', + nameKey: 'settings.integrations.messengers.telegram.name', + descriptionKey: 'settings.integrations.messengers.telegram.description', + }, +] as const; + +/** + * Non-interactive Discord/Telegram placeholders — same card chrome as live + * integrations, greyed out, with a Coming soon badge and no expandable body. + */ +export const ComingSoonMessengersSection: React.FC = () => { + const { t } = useI18n(); + + return ( + + {COMING_SOON_MESSENGERS.map((messenger) => ( +
+
+ +
+
+
{t(messenger.nameKey)}
+

+ {t(messenger.descriptionKey)} +

+
+ + {t('settings.common.state.comingSoon')} + +
+ ))} +
+ ); +}; diff --git a/packages/ui/src/components/sections/integrations/IntegrationsPage.tsx b/packages/ui/src/components/sections/integrations/IntegrationsPage.tsx new file mode 100644 index 00000000..f07ce340 --- /dev/null +++ b/packages/ui/src/components/sections/integrations/IntegrationsPage.tsx @@ -0,0 +1,30 @@ +import React from 'react'; +import { SettingsPageLayout } from '@/components/sections/shared/SettingsPageLayout'; +import { useI18n } from '@/lib/i18n'; +import { ThirdPartyIntegrationsSection } from './ThirdPartyIntegrationsSection'; + +interface IntegrationsPageProps { + onOpenProviderSetup: (providerId: string) => Promise; + onOpenPluginManager: () => void; +} + +export const IntegrationsPage: React.FC = ({ + onOpenProviderSetup, + onOpenPluginManager, +}) => { + const { t } = useI18n(); + + return ( + + + + ); +}; diff --git a/packages/ui/src/components/sections/integrations/ThirdPartyIntegrationsSection.tsx b/packages/ui/src/components/sections/integrations/ThirdPartyIntegrationsSection.tsx new file mode 100644 index 00000000..f0b7cce6 --- /dev/null +++ b/packages/ui/src/components/sections/integrations/ThirdPartyIntegrationsSection.tsx @@ -0,0 +1,447 @@ +import React from 'react'; +import { useShallow } from 'zustand/react/shallow'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { toast } from '@/components/ui'; +import { Icon } from '@/components/icon/Icon'; +import { SettingsSection } from '@/components/sections/shared/SettingsSection'; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; +import { ProviderLogo } from '@/components/ui/ProviderLogo'; +import { useI18n } from '@/lib/i18n'; +import { openExternalUrl } from '@/lib/url'; +import { cn } from '@/lib/utils'; +import { + usePluginsStore, + type PluginMutationResult, +} from '@/stores/usePluginsStore'; +import { usePendingOpenCodeRestartStore } from '@/stores/usePendingOpenCodeRestartStore'; +import { + getCatalogPluginPrimaryAction, + getCatalogPluginPresentation, + getCatalogPluginState, + getLatestNpmSpec, + THIRD_PARTY_PLUGINS, + type ThirdPartyPluginDefinition, +} from './thirdPartyPlugins'; + +type PendingAction = 'install' | 'update' | 'setup' | 'remove'; + +type RemoveTarget = ThirdPartyPluginDefinition | null; + +interface ThirdPartyIntegrationsSectionProps { + divider?: boolean; + onOpenProviderSetup: (providerId: string) => Promise; + onOpenPluginManager: () => void; +} + +const requiresRestart = (result: PluginMutationResult): boolean => + result.restartDeferred === true + || result.requiresManualRestart === true + || result.reloadFailed === true; + +export const ThirdPartyIntegrationsSection: React.FC = ({ + divider = true, + onOpenProviderSetup, + onOpenPluginManager, +}) => { + const { t } = useI18n(); + const { + entries, + registryInfo, + loadPlugins, + loadRegistryInfo, + createEntry, + updateEntry, + deleteEntry, + } = usePluginsStore( + useShallow((state) => ({ + entries: state.entries, + registryInfo: state.registryInfo, + loadPlugins: state.loadPlugins, + loadRegistryInfo: state.loadRegistryInfo, + createEntry: state.createEntry, + updateEntry: state.updateEntry, + deleteEntry: state.deleteEntry, + })), + ); + + const [registryLoadFailed, setRegistryLoadFailed] = React.useState(false); + const [pendingAction, setPendingAction] = React.useState<{ + pluginId: string; + action: PendingAction; + } | null>(null); + const [restartRequiredIds, setRestartRequiredIds] = React.useState>( + () => new Set(), + ); + const [providerUnavailableIds, setProviderUnavailableIds] = React.useState>( + () => new Set(), + ); + const [removeTarget, setRemoveTarget] = React.useState(null); + const [openPluginIds, setOpenPluginIds] = React.useState>(() => new Set()); + + const refresh = React.useCallback(async () => { + const pluginsLoaded = await loadPlugins({ force: true }); + if (!pluginsLoaded) { + setRegistryLoadFailed(true); + return; + } + + const latestEntries = usePluginsStore.getState().entries; + const specs = new Set(THIRD_PARTY_PLUGINS.map((plugin) => plugin.packageName)); + for (const entry of latestEntries) { + if (THIRD_PARTY_PLUGINS.some((plugin) => entry.spec === plugin.packageName || entry.spec.startsWith(`${plugin.packageName}@`))) { + specs.add(entry.spec); + } + } + const registryLoaded = await loadRegistryInfo({ specs: [...specs], force: true }); + setRegistryLoadFailed(!registryLoaded); + }, [loadPlugins, loadRegistryInfo]); + + React.useEffect(() => { + void refresh(); + }, [refresh]); + + const pendingPluginRestartCount = usePendingOpenCodeRestartStore( + (state) => state.changes.filter((change) => change.scope === 'plugins').length, + ); + const isApplyingRestart = usePendingOpenCodeRestartStore((state) => state.isApplying); + const previousPluginRestartCountRef = React.useRef(pendingPluginRestartCount); + + // When deferred plugin restarts are applied (pending plugins scope clears), drop + // local restart/unavailable flags and reload so statuses update immediately. + React.useEffect(() => { + const previousCount = previousPluginRestartCountRef.current; + previousPluginRestartCountRef.current = pendingPluginRestartCount; + + if (isApplyingRestart) { + return; + } + if (previousCount <= 0 || pendingPluginRestartCount > 0) { + return; + } + + setRestartRequiredIds(new Set()); + setProviderUnavailableIds(new Set()); + void refresh(); + }, [isApplyingRestart, pendingPluginRestartCount, refresh]); + + const setRestartRequired = React.useCallback((pluginId: string, required: boolean) => { + setRestartRequiredIds((current) => { + const next = new Set(current); + if (required) next.add(pluginId); + else next.delete(pluginId); + return next; + }); + }, []); + + const setProviderUnavailable = React.useCallback((pluginId: string, unavailable: boolean) => { + setProviderUnavailableIds((current) => { + const next = new Set(current); + if (unavailable) next.add(pluginId); + else next.delete(pluginId); + return next; + }); + }, []); + + const runMutation = React.useCallback(async ( + plugin: ThirdPartyPluginDefinition, + action: Exclude, + run: () => Promise, + ) => { + setPendingAction({ pluginId: plugin.id, action }); + try { + const result = await run(); + if (!result.ok) { + toast.error(t('settings.integrations.thirdParty.toast.actionFailed')); + return; + } + + setProviderUnavailable(plugin.id, false); + const restartNeeded = requiresRestart(result); + setRestartRequired(plugin.id, restartNeeded); + const toastOptions = restartNeeded + ? { description: t('settings.integrations.thirdParty.toast.restartRequired') } + : undefined; + if (action === 'install') { + toast.success(t('settings.integrations.thirdParty.toast.installed', { name: t(plugin.nameKey) }), toastOptions); + } else if (action === 'update') { + toast.success(t('settings.integrations.thirdParty.toast.updated', { name: t(plugin.nameKey) }), toastOptions); + } else { + toast.success(t('settings.integrations.thirdParty.toast.removed', { name: t(plugin.nameKey) }), toastOptions); + } + await refresh(); + } finally { + setPendingAction(null); + } + }, [refresh, setProviderUnavailable, setRestartRequired, t]); + + const handlePrimaryAction = React.useCallback(async (plugin: ThirdPartyPluginDefinition) => { + const state = getCatalogPluginState(entries, plugin.packageName, registryInfo); + const action = getCatalogPluginPrimaryAction(state, plugin.packageName); + + if (action === 'manage') { + onOpenPluginManager(); + return; + } + + if (action === 'setup') { + setPendingAction({ pluginId: plugin.id, action }); + try { + const opened = await onOpenProviderSetup(plugin.providerId); + setProviderUnavailable(plugin.id, !opened); + if (!opened) { + toast.error(t('settings.integrations.thirdParty.toast.providerUnavailable')); + } + } finally { + setPendingAction(null); + } + return; + } + + const latestSpec = getLatestNpmSpec(plugin.packageName, state.registry); + if (!latestSpec) { + setRegistryLoadFailed(true); + return; + } + + if (action === 'install') { + await runMutation(plugin, 'install', () => createEntry({ spec: latestSpec, scope: 'user' })); + return; + } + + if (state.userEntry) { + await runMutation(plugin, 'update', () => updateEntry(state.userEntry!.id, { spec: latestSpec })); + } + }, [createEntry, entries, onOpenPluginManager, onOpenProviderSetup, registryInfo, runMutation, setProviderUnavailable, t, updateEntry]); + + const handleRemove = React.useCallback(async () => { + const plugin = removeTarget; + if (!plugin) return; + const state = getCatalogPluginState(entries, plugin.packageName, registryInfo); + if (!state.userEntry || state.userEntryIsAmbiguous) { + setRemoveTarget(null); + onOpenPluginManager(); + return; + } + setRemoveTarget(null); + await runMutation(plugin, 'remove', () => deleteEntry(state.userEntry!.id)); + }, [deleteEntry, entries, onOpenPluginManager, registryInfo, removeTarget, runMutation]); + + const setPluginOpen = React.useCallback((pluginId: string, open: boolean) => { + setOpenPluginIds((current) => { + const next = new Set(current); + if (open) next.add(pluginId); + else next.delete(pluginId); + return next; + }); + }, []); + + const renderPlugin = (plugin: ThirdPartyPluginDefinition) => { + const state = getCatalogPluginState(entries, plugin.packageName, registryInfo); + const primaryAction = getCatalogPluginPrimaryAction(state, plugin.packageName); + const latestSpec = getLatestNpmSpec(plugin.packageName, state.registry); + const isPending = pendingAction?.pluginId === plugin.id; + const isRestartRequired = restartRequiredIds.has(plugin.id); + const isProviderUnavailable = providerUnavailableIds.has(plugin.id); + const registryUnavailable = registryLoadFailed || state.registry?.kind === 'npm-network'; + const actionDisabled = isPending + || isRestartRequired + || ((primaryAction === 'install' || primaryAction === 'update') && (registryUnavailable || !latestSpec)); + const presentation = getCatalogPluginPresentation(state, { + registryUnavailable, + restartRequired: isRestartRequired, + providerUnavailable: isProviderUnavailable, + }); + let status: string; + switch (presentation.status) { + case 'installed-version': + status = presentation.latestVersion + ? t('settings.integrations.thirdParty.status.installedVersion', { + version: presentation.latestVersion, + }) + : t('settings.integrations.thirdParty.status.installed'); + break; + case 'update-available': + status = presentation.latestVersion + ? t('settings.integrations.thirdParty.status.updateAvailable', { + version: presentation.latestVersion, + }) + : t('settings.integrations.thirdParty.status.unpinned'); + break; + case 'not-installed': + status = t('settings.integrations.thirdParty.status.notInstalled'); + break; + case 'installed': + status = t('settings.integrations.thirdParty.status.installed'); + break; + case 'unpinned': + status = t('settings.integrations.thirdParty.status.unpinned'); + break; + case 'ambiguous': + status = t('settings.integrations.thirdParty.status.ambiguous'); + break; + case 'restart-required': + status = t('settings.integrations.thirdParty.status.restartRequired'); + break; + case 'registry-unavailable': + status = t('settings.integrations.thirdParty.status.registryUnavailable'); + break; + case 'provider-unavailable': + status = t('settings.integrations.thirdParty.status.providerUnavailable'); + break; + } + const statusClassName = presentation.status === 'installed-version' + ? 'bg-[var(--status-success)]/15 text-[var(--status-success)]' + : presentation.status === 'update-available' + || presentation.status === 'ambiguous' + || presentation.status === 'restart-required' + || presentation.status === 'registry-unavailable' + || presentation.status === 'provider-unavailable' + ? 'bg-[var(--status-warning)]/15 text-[var(--status-warning)]' + : 'bg-[var(--surface-muted)] text-muted-foreground'; + + const primaryLabel = { + install: t('settings.integrations.thirdParty.actions.install'), + update: t('settings.integrations.thirdParty.actions.update'), + setup: t('settings.integrations.thirdParty.actions.setup'), + manage: t('settings.integrations.thirdParty.actions.managePlugins'), + }[primaryAction]; + + const open = openPluginIds.has(plugin.id); + + return ( + setPluginOpen(plugin.id, nextOpen)} + > +
+ +
+ {plugin.providerId === 'command-code' ? ( + + ) : ( + + )} +
+
+
{t(plugin.nameKey)}
+

+ {t(plugin.descriptionKey)} +

+
+ + {status} + + +
+ +
+ {state.projectEntries.length > 0 ? ( +

+ {t('settings.integrations.thirdParty.status.projectInstalled')} +

+ ) : null} +
+ + + {state.userEntry && !state.userEntryIsAmbiguous ? ( + + ) : null} +
+
+
+
+
+ ); + }; + + return ( + <> + + {THIRD_PARTY_PLUGINS.map(renderPlugin)} + + + !open && setRemoveTarget(null)}> + + + {t('settings.integrations.thirdParty.dialog.remove.title')} + + {t('settings.integrations.thirdParty.dialog.remove.description', { + name: removeTarget ? t(removeTarget.nameKey) : '', + })} + + + + + + + + + + ); +}; diff --git a/packages/ui/src/components/sections/integrations/thirdPartyPlugins.test.ts b/packages/ui/src/components/sections/integrations/thirdPartyPlugins.test.ts new file mode 100644 index 00000000..35dc0846 --- /dev/null +++ b/packages/ui/src/components/sections/integrations/thirdPartyPlugins.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, test } from 'bun:test'; +import type { PluginEntry, RegistryResult } from '@/stores/usePluginsStore'; +import * as thirdPartyCatalog from './thirdPartyPlugins'; +import { + getCatalogPluginState, + getCatalogPluginPrimaryAction, + getLatestNpmSpec, + specMatchesPackage, +} from './thirdPartyPlugins'; + +type CatalogPresentationStatus = + | 'not-installed' + | 'installed' + | 'installed-version' + | 'update-available' + | 'unpinned' + | 'ambiguous' + | 'restart-required' + | 'registry-unavailable' + | 'provider-unavailable'; + +type GetCatalogPluginPresentation = ( + state: ReturnType, + options?: { + registryUnavailable?: boolean; + restartRequired?: boolean; + providerUnavailable?: boolean; + }, +) => { + status: CatalogPresentationStatus; + latestVersion: string | null; +}; + +const getCatalogPluginPresentation = ( + thirdPartyCatalog as unknown as { + getCatalogPluginPresentation?: GetCatalogPluginPresentation; + } +).getCatalogPluginPresentation; + +const claudePackage = '@openchamber/opencode-claude'; + +const entry = (spec: string, scope: PluginEntry['scope'] = 'user'): PluginEntry => ({ + id: `config:${scope}:${spec}`, + spec, + scope, + kind: 'config', + parsedKind: 'npm', +}); + +const registry = (spec: string, currentVersion: string | null, latestVersion = '0.7.0'): RegistryResult => ({ + kind: 'npm-ok', + spec, + name: claudePackage, + currentVersion, + latestVersion, + versions: ['0.6.0', latestVersion], + hasUpdate: currentVersion !== null && currentVersion !== latestVersion, +}); + +describe('third-party plugin catalog helpers', () => { + test('derives compact-card status with explicit transient-state priority', () => { + expect(typeof getCatalogPluginPresentation).toBe('function'); + if (!getCatalogPluginPresentation) return; + + const notInstalled = getCatalogPluginState([], claudePackage, {}); + expect(getCatalogPluginPresentation(notInstalled)).toEqual({ + status: 'not-installed', + latestVersion: null, + }); + + const current = getCatalogPluginState( + [entry(`${claudePackage}@0.7.0`)], + claudePackage, + { [`${claudePackage}@0.7.0`]: registry(`${claudePackage}@0.7.0`, '0.7.0') }, + ); + expect(getCatalogPluginPresentation(current)).toEqual({ + status: 'installed-version', + latestVersion: '0.7.0', + }); + + const outdated = getCatalogPluginState( + [entry(`${claudePackage}@0.6.0`)], + claudePackage, + { [`${claudePackage}@0.6.0`]: registry(`${claudePackage}@0.6.0`, '0.6.0') }, + ); + expect(getCatalogPluginPresentation(outdated)).toEqual({ + status: 'update-available', + latestVersion: '0.7.0', + }); + expect(getCatalogPluginPresentation(outdated, { registryUnavailable: true })).toEqual({ + status: 'registry-unavailable', + latestVersion: '0.7.0', + }); + expect(getCatalogPluginPresentation(outdated, { providerUnavailable: true })).toEqual({ + status: 'provider-unavailable', + latestVersion: '0.7.0', + }); + expect(getCatalogPluginPresentation(outdated, { + providerUnavailable: true, + restartRequired: true, + })).toEqual({ + status: 'restart-required', + latestVersion: '0.7.0', + }); + + const ambiguous = getCatalogPluginState( + [entry(claudePackage), entry(`${claudePackage}@0.6.0`)], + claudePackage, + {}, + ); + expect(getCatalogPluginPresentation(ambiguous)).toEqual({ + status: 'ambiguous', + latestVersion: null, + }); + }); + + test('matches only a package or its versioned spec', () => { + expect(specMatchesPackage(claudePackage, claudePackage)).toBe(true); + expect(specMatchesPackage(`${claudePackage}@0.6.0`, claudePackage)).toBe(true); + expect(specMatchesPackage('@openchamber/opencode-claude-extra@0.6.0', claudePackage)).toBe(false); + }); + + test('points catalog plugins at the OpenChamber GitHub and npm packages', () => { + expect(thirdPartyCatalog.THIRD_PARTY_PLUGINS.map((plugin) => ({ + id: plugin.id, + packageName: plugin.packageName, + homepage: plugin.homepage, + }))).toEqual([ + { + id: 'opencode-claude', + packageName: '@openchamber/opencode-claude', + homepage: 'https://github.com/openchamber/opencode-claude', + }, + { + id: 'opencode-commandcode', + packageName: '@openchamber/opencode-commandcode', + homepage: 'https://github.com/openchamber/opencode-commandcode', + }, + { + id: 'opencode-cursor-oauth', + packageName: '@openchamber/opencode-cursor', + homepage: 'https://github.com/openchamber/opencode-cursor', + }, + ]); + }); + + test('uses the configured user entry and its registry result', () => { + const installed = entry(`${claudePackage}@0.6.0`); + const state = getCatalogPluginState( + [installed], + claudePackage, + { [installed.spec]: registry(installed.spec, '0.6.0') }, + ); + + expect(state.userEntry).toEqual(installed); + expect(state.userEntryIsAmbiguous).toBe(false); + expect(state.projectEntries).toEqual([]); + expect(state.registry).toEqual(registry(installed.spec, '0.6.0')); + }); + + test('does not choose an entry when multiple user specs would make a mutation ambiguous', () => { + const state = getCatalogPluginState( + [entry(claudePackage), entry(`${claudePackage}@0.6.0`), entry(claudePackage, 'project')], + claudePackage, + {}, + ); + + expect(state.userEntry).toBeNull(); + expect(state.userEntryIsAmbiguous).toBe(true); + expect(state.projectEntries).toHaveLength(1); + }); + + test('returns an exact latest spec only from a valid npm registry result', () => { + expect(getLatestNpmSpec(claudePackage, registry(claudePackage, null))).toBe(`${claudePackage}@0.7.0`); + expect(getLatestNpmSpec(claudePackage, { + kind: 'npm-network', + spec: claudePackage, + error: 'offline', + })).toBeNull(); + }); + + test('chooses an update for a bare or outdated user-wide entry', () => { + const bare = getCatalogPluginState( + [entry(claudePackage)], + claudePackage, + { [claudePackage]: registry(claudePackage, null) }, + ); + const outdated = getCatalogPluginState( + [entry(`${claudePackage}@0.6.0`)], + claudePackage, + { [`${claudePackage}@0.6.0`]: registry(`${claudePackage}@0.6.0`, '0.6.0') }, + ); + + expect(getCatalogPluginPrimaryAction(bare, claudePackage)).toBe('update'); + expect(getCatalogPluginPrimaryAction(outdated, claudePackage)).toBe('update'); + }); + + test('keeps setup as the primary action once the exact latest spec is installed', () => { + const installed = entry(`${claudePackage}@0.7.0`); + const state = getCatalogPluginState( + [installed], + claudePackage, + { [installed.spec]: registry(installed.spec, '0.7.0') }, + ); + + expect(getCatalogPluginPrimaryAction(state, claudePackage)).toBe('setup'); + }); + + test('sends ambiguous entries to manual plugin management', () => { + const state = getCatalogPluginState( + [entry(claudePackage), entry(`${claudePackage}@0.6.0`)], + claudePackage, + {}, + ); + + expect(getCatalogPluginPrimaryAction(state, claudePackage)).toBe('manage'); + }); +}); diff --git a/packages/ui/src/components/sections/integrations/thirdPartyPlugins.ts b/packages/ui/src/components/sections/integrations/thirdPartyPlugins.ts new file mode 100644 index 00000000..ecbf1bba --- /dev/null +++ b/packages/ui/src/components/sections/integrations/thirdPartyPlugins.ts @@ -0,0 +1,166 @@ +import type { IconName } from '@/components/icon/icons'; +import type { I18nKey } from '@/lib/i18n'; +import type { PluginEntry, RegistryResult } from '@/stores/usePluginsStore'; + +export interface ThirdPartyPluginDefinition { + id: string; + packageName: string; + providerId: string; + icon: IconName; + /** Brand mark tint (e.g. Claude orange); neutral marks use text-foreground. */ + brandClassName: string; + nameKey: I18nKey; + descriptionKey: I18nKey; + homepage: string; +} + +export const THIRD_PARTY_PLUGINS: readonly ThirdPartyPluginDefinition[] = [ + { + id: 'opencode-claude', + packageName: '@openchamber/opencode-claude', + providerId: 'claude-code', + icon: 'claude-code', + brandClassName: 'text-[#D97757]', + nameKey: 'settings.integrations.thirdParty.opencodeClaude.name', + descriptionKey: 'settings.integrations.thirdParty.opencodeClaude.description', + homepage: 'https://github.com/openchamber/opencode-claude', + }, + { + id: 'opencode-commandcode', + packageName: '@openchamber/opencode-commandcode', + providerId: 'command-code', + icon: 'command-code', + brandClassName: 'text-foreground', + nameKey: 'settings.integrations.thirdParty.opencodeCommandcode.name', + descriptionKey: 'settings.integrations.thirdParty.opencodeCommandcode.description', + homepage: 'https://github.com/openchamber/opencode-commandcode', + }, + { + id: 'opencode-cursor-oauth', + packageName: '@openchamber/opencode-cursor', + providerId: 'cursor', + icon: 'cursor', + brandClassName: 'text-foreground', + nameKey: 'settings.integrations.thirdParty.opencodeCursorOauth.name', + descriptionKey: 'settings.integrations.thirdParty.opencodeCursorOauth.description', + homepage: 'https://github.com/openchamber/opencode-cursor', + }, +] as const; + +export interface CatalogPluginState { + userEntry: PluginEntry | null; + userEntryIsAmbiguous: boolean; + projectEntries: PluginEntry[]; + registry: RegistryResult | null; +} + +export type CatalogPluginPrimaryAction = 'install' | 'update' | 'setup' | 'manage'; + +type CatalogPluginPresentationStatus = + | 'not-installed' + | 'installed' + | 'installed-version' + | 'update-available' + | 'unpinned' + | 'ambiguous' + | 'restart-required' + | 'registry-unavailable' + | 'provider-unavailable'; + +interface CatalogPluginPresentationOptions { + registryUnavailable?: boolean; + restartRequired?: boolean; + providerUnavailable?: boolean; +} + +interface CatalogPluginPresentation { + status: CatalogPluginPresentationStatus; + latestVersion: string | null; +} + +export const specMatchesPackage = (spec: string, packageName: string): boolean => + spec === packageName || spec.startsWith(`${packageName}@`); + +export function getCatalogPluginState( + entries: PluginEntry[], + packageName: string, + registryInfo: Record, +): CatalogPluginState { + const matchingEntries = entries.filter((entry) => specMatchesPackage(entry.spec, packageName)); + const userEntries = matchingEntries.filter((entry) => entry.scope === 'user'); + const projectEntries = matchingEntries.filter((entry) => entry.scope === 'project'); + const userEntry = userEntries.length === 1 ? userEntries[0] : null; + const registry = registryInfo[userEntry?.spec ?? packageName] ?? registryInfo[packageName] ?? null; + + return { + userEntry, + userEntryIsAmbiguous: userEntries.length > 1, + projectEntries, + registry, + }; +} + +export function getLatestNpmSpec( + packageName: string, + registry: RegistryResult | null | undefined, +): string | null { + if (registry?.kind !== 'npm-ok' || registry.name !== packageName || !registry.latestVersion) { + return null; + } + return `${packageName}@${registry.latestVersion}`; +} + +export function getCatalogPluginPrimaryAction( + state: CatalogPluginState, + packageName: string, +): CatalogPluginPrimaryAction { + if (state.userEntryIsAmbiguous) { + return 'manage'; + } + + if (!state.userEntry) { + return 'install'; + } + + const latestSpec = getLatestNpmSpec(packageName, state.registry); + return latestSpec && latestSpec !== state.userEntry.spec ? 'update' : 'setup'; +} + +/** + * Converts catalog and temporary mutation state into the one compact-card + * status. Transient states intentionally outrank installed/version metadata. + */ +export function getCatalogPluginPresentation( + state: CatalogPluginState, + options: CatalogPluginPresentationOptions = {}, +): CatalogPluginPresentation { + const latestVersion = state.registry?.kind === 'npm-ok' + ? state.registry.latestVersion + : null; + + if (state.userEntryIsAmbiguous) { + return { status: 'ambiguous', latestVersion }; + } + if (options.restartRequired) { + return { status: 'restart-required', latestVersion }; + } + if (options.providerUnavailable) { + return { status: 'provider-unavailable', latestVersion }; + } + if (options.registryUnavailable) { + return { status: 'registry-unavailable', latestVersion }; + } + if (!state.userEntry) { + return { status: 'not-installed', latestVersion }; + } + if (state.registry?.kind === 'npm-ok' && state.registry.currentVersion === state.registry.latestVersion) { + return { status: 'installed-version', latestVersion }; + } + if (state.registry?.kind === 'npm-ok' && state.registry.currentVersion === null) { + return { status: 'unpinned', latestVersion }; + } + if (state.registry?.kind === 'npm-ok' && latestVersion) { + return { status: 'update-available', latestVersion }; + } + return { status: 'installed', latestVersion }; +} diff --git a/packages/ui/src/components/sections/openchamber/DefaultsSettings.tsx b/packages/ui/src/components/sections/openchamber/DefaultsSettings.tsx index a3001a89..72db4ddd 100644 --- a/packages/ui/src/components/sections/openchamber/DefaultsSettings.tsx +++ b/packages/ui/src/components/sections/openchamber/DefaultsSettings.tsx @@ -52,7 +52,7 @@ export const DefaultsSettings: React.FC = () => { const [defaultAgent, setDefaultAgent] = React.useState(); const [smallModelUseDefault, setSmallModelUseDefault] = React.useState(true); const [smallModelOverride, setSmallModelOverride] = React.useState(); - const [smallModelProviders, setSmallModelProviders] = React.useState(); + const [smallModelProviders, setSmallModelProviders] = React.useState([]); const [walkthroughModelOverride, setWalkthroughModelOverride] = React.useState(); const [isLoading, setIsLoading] = React.useState(true); @@ -274,13 +274,12 @@ export const DefaultsSettings: React.FC = () => { () => getDisplayModel(walkthroughModelOverride), [walkthroughModelOverride] ); - React.useEffect(() => { - // Both pickers filter by the same authenticated-provider list, so either - // one being open is reason enough to fetch it. - // Both pickers filter by the same authenticated-provider list, and the - // walkthrough picker is always visible, so this is always worth fetching. - if (smallModelProviders !== undefined) return; + // Both pickers offer the same providers — the walkthrough runs through the + // small model — and the walkthrough picker is always visible, so this is + // always worth fetching. The server answers with the providers it has a + // credential and an endpoint for, including plugin-registered ones that + // exist only inside the running OpenCode. let cancelled = false; (async () => { try { @@ -291,13 +290,13 @@ export const DefaultsSettings: React.FC = () => { setSmallModelProviders(payload.authenticatedProviders.filter((id): id is string => typeof id === 'string')); } } catch { - // leave undefined — picker falls back to showing all providers + // Fail closed: never offer providers whose credentials were not verified. } })(); return () => { cancelled = true; }; - }, [smallModelProviders]); + }, []); const availableVariants = React.useMemo(() => { if (!parsedModel.providerId || !parsedModel.modelId) return []; diff --git a/packages/ui/src/components/sections/openchamber/OpenChamberToolsSettings.tsx b/packages/ui/src/components/sections/openchamber/OpenChamberToolsSettings.tsx index df8cfbed..46b0bcf2 100644 --- a/packages/ui/src/components/sections/openchamber/OpenChamberToolsSettings.tsx +++ b/packages/ui/src/components/sections/openchamber/OpenChamberToolsSettings.tsx @@ -7,6 +7,7 @@ import { } from '@/components/sections/shared/SettingsSection'; import { recordDeferredOpenCodeRestart } from '@/lib/opencode/deferredRestart'; import { updateDesktopSettings } from '@/lib/persistence'; +import { useAgentMemoryStore } from '@/stores/useAgentMemoryStore'; import { useUIStore } from '@/stores/useUIStore'; import { useI18n } from '@/lib/i18n'; @@ -27,6 +28,11 @@ export const OpenChamberToolsSettings: React.FC = () => { const setAgentControlToolEnabled = useUIStore((state) => state.setAgentControlToolEnabled); const agentWebToolEnabled = useUIStore((state) => state.agentWebToolEnabled); const setAgentWebToolEnabled = useUIStore((state) => state.setAgentWebToolEnabled); + const agentMemoryToolEnabled = useUIStore((state) => state.agentMemoryToolEnabled); + // Absent, not merely off: the feature is finished but unreleased, and a + // visible switch invites turning on something that was never announced. + const agentMemoryAvailable = useUIStore((state) => state.agentMemoryFeatureAvailable); + const setAgentMemoryToolEnabled = useUIStore((state) => state.setAgentMemoryToolEnabled); const handleAgentControlToolChange = React.useCallback((enabled: boolean) => { setAgentControlToolEnabled(enabled); @@ -40,6 +46,24 @@ export const OpenChamberToolsSettings: React.FC = () => { recordDeferredOpenCodeRestart('cli', { id: 'agent-web-tool' }); }, [setAgentWebToolEnabled]); + // Turning memory off removes the whole feature, not just the tool: the panel + // tab goes with it and sessions stop being given the index. Showing the user + // what is stored would be pointless once the agent can no longer manage it. + const handleAgentMemoryToolChange = React.useCallback((enabled: boolean) => { + setAgentMemoryToolEnabled(enabled); + // Re-read after the write lands, not before. The switch flips the client + // immediately, which makes the panel ask the server straight away — and + // while the setting is still being written the server truthfully answers + // "disabled", which used to leave the tab hidden until a restart. + void updateDesktopSettings({ agentMemoryToolEnabled: enabled }) + .finally(() => { + if (enabled) { + void useAgentMemoryStore.getState().refresh(); + } + }); + recordDeferredOpenCodeRestart('cli', { id: 'agent-memory-tool' }); + }, [setAgentMemoryToolEnabled]); + return (
@@ -60,6 +84,17 @@ export const OpenChamberToolsSettings: React.FC = () => { ariaLabel={t('settings.openchamber.tools.field.agentWebToolAria')} info={t('settings.openchamber.tools.field.agentWebToolInfo')} /> + + {agentMemoryAvailable ? ( + + ) : null}
); diff --git a/packages/ui/src/components/sections/providers/CustomProviderForm.tsx b/packages/ui/src/components/sections/providers/CustomProviderForm.tsx index 6fce317e..557151d2 100644 --- a/packages/ui/src/components/sections/providers/CustomProviderForm.tsx +++ b/packages/ui/src/components/sections/providers/CustomProviderForm.tsx @@ -10,9 +10,11 @@ import { } from '@/components/sections/shared/SettingsSection'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Icon } from '@/components/icon/Icon'; import { useI18n } from '@/lib/i18n'; import { + CUSTOM_PROVIDER_PROTOCOLS, createEmptyCustomProviderForm, createHeaderRow, createModelRow, @@ -161,6 +163,31 @@ export const CustomProviderForm: React.FC = ({ {err.providerID ?

{err.providerID}

: null} + + + + = ({ return; } - if (authorization.url) { + // Claude Code CLI owns its OAuth flow and opens the browser itself. Its + // plugin URL is informational only; opening it creates a misleading docs + // tab alongside the real sign-in page. + if (authorization.url && shouldOpenAuthorizationUrl(providerId, authorization.url)) { void openExternalUrl(authorization.url); } diff --git a/packages/ui/src/components/sections/providers/ProvidersPage.test.ts b/packages/ui/src/components/sections/providers/ProvidersPage.test.ts index 448dcc6e..05050304 100644 --- a/packages/ui/src/components/sections/providers/ProvidersPage.test.ts +++ b/packages/ui/src/components/sections/providers/ProvidersPage.test.ts @@ -1,9 +1,10 @@ import { describe, expect, test } from 'bun:test'; -import { shouldLoadAvailableProviders } from './providerAvailability'; +import { requiresProviderAuth, shouldLoadAvailableProviders } from './providerAvailability'; import { getOAuthAuthMethods, normalizeAuthType, parseAuthPayload, + requiresOpenCodeRestartAfterOAuth, shouldShowApiKeyAuth, } from './providerAuth'; @@ -14,6 +15,14 @@ describe('ProvidersPage available provider loading', () => { }); }); +describe('ProvidersPage provider authentication', () => { + test('does not require credentials for a custom provider defined in config', () => { + expect(requiresProviderAuth(true, false, true)).toBe(false); + expect(requiresProviderAuth(true, false, false)).toBe(true); + expect(requiresProviderAuth(true, true, false)).toBe(false); + }); +}); + describe('provider auth method helpers', () => { test('normalizeAuthType recognizes oauth and api labels', () => { expect(normalizeAuthType({ type: 'oauth', label: 'Login with Cursor' })).toBe('oauth'); @@ -57,4 +66,9 @@ describe('provider auth method helpers', () => { { method: { type: 'oauth', label: 'Cursor' }, methodIndex: 0 }, ]); }); + + test('Claude CLI OAuth does not require an OpenCode restart', () => { + expect(requiresOpenCodeRestartAfterOAuth('claude-code')).toBe(false); + expect(requiresOpenCodeRestartAfterOAuth('github-copilot')).toBe(true); + }); }); diff --git a/packages/ui/src/components/sections/providers/ProvidersPage.tsx b/packages/ui/src/components/sections/providers/ProvidersPage.tsx index 2dfc607d..6a4655f5 100644 --- a/packages/ui/src/components/sections/providers/ProvidersPage.tsx +++ b/packages/ui/src/components/sections/providers/ProvidersPage.tsx @@ -23,10 +23,11 @@ import type { ModelMetadata } from '@/types'; import { getCurrentIntlLocale, useI18n } from '@/lib/i18n'; import { runtimeFetch } from '@/lib/runtime-fetch'; import { opencodeClient } from '@/lib/opencode/client'; -import { shouldLoadAvailableProviders } from './providerAvailability'; +import { requiresProviderAuth, shouldLoadAvailableProviders } from './providerAvailability'; import { getOAuthAuthMethods, parseAuthPayload, + requiresOpenCodeRestartAfterOAuth, shouldShowApiKeyAuth, type AuthMethod, type OAuthAuthMethodEntry, @@ -323,7 +324,8 @@ export const ProvidersPage: React.FC = () => { ? provider.env.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0) : []; const hasCreds = Boolean(sources.auth.exists) || envEntries.length > 0; - if (!hasCreds) { + const isCustomProvider = Boolean(provider && isConfigDefinedCustomProvider(provider, sources)); + if (requiresProviderAuth(true, hasCreds, isCustomProvider)) { setShowAuthPanel(true); } }, [selectedProviderId, providerSources, providers]); @@ -471,7 +473,9 @@ export const ProvidersPage: React.FC = () => { const handleOAuthConnected = (providerId: string) => { setShowAuthPanel(false); - recordDeferredOpenCodeRestart('providers', { id: providerId }); + if (requiresOpenCodeRestartAfterOAuth(providerId)) { + recordDeferredOpenCodeRestart('providers', { id: providerId }); + } setSelectedProvider(providerId); }; @@ -770,8 +774,12 @@ export const ProvidersPage: React.FC = () => { const hasStoredAuth = Boolean(selectedSources?.auth.exists); const hasEnvCredentials = providerEnv.length > 0; const hasCredentials = hasStoredAuth || hasEnvCredentials; - const authStatusIncomplete = sourcesLoaded && !hasCredentials; - const showModelsSection = providerModels.length > 0 && (!sourcesLoaded || hasCredentials); + const authStatusIncomplete = requiresProviderAuth( + sourcesLoaded, + hasCredentials, + isEditableCustomProvider, + ); + const showModelsSection = providerModels.length > 0 && !authStatusIncomplete; const incompleteAuthHint = !showApiKeyAuth && oauthAuthMethods.length > 0 ? t('settings.providers.page.auth.useReconnectHint') : t('settings.providers.page.auth.incompleteHint'); diff --git a/packages/ui/src/components/sections/providers/custom-provider-form.test.ts b/packages/ui/src/components/sections/providers/custom-provider-form.test.ts index a8b5c930..76812ec8 100644 --- a/packages/ui/src/components/sections/providers/custom-provider-form.test.ts +++ b/packages/ui/src/components/sections/providers/custom-provider-form.test.ts @@ -16,6 +16,7 @@ const t = (key: string) => key; const baseForm = (overrides: Partial = {}): CustomProviderFormState => ({ providerID: 'custom-provider', name: 'Custom Provider', + protocol: 'openai-chat', baseURL: 'https://api.example.com/v1', apiKey: 'sk-test', models: [{ row: 'm0', id: 'model-a', name: 'Model A' }], @@ -96,6 +97,16 @@ describe('validateCustomProvider', () => { expect(result.result?.config.env).toEqual(['CUSTOM_PROVIDER_KEY']); }); + test('uses the selected OpenCode provider adapter', () => { + const result = validateCustomProvider({ + form: baseForm({ protocol: 'openai-responses' }), + t, + existingProviderIDs: new Set(), + }); + + expect(result.result?.config.npm).toBe('@ai-sdk/openai'); + }); + test('rejects missing credentials', () => { const result = validateCustomProvider({ form: baseForm({ apiKey: ' ' }), @@ -300,10 +311,21 @@ describe('provider edit helpers', () => { expect(state.name).toBe('Campus LLM'); expect(state.baseURL).toBe('https://llm.example.edu/v1'); expect(state.apiKey).toBe('{env:CAMPUS_KEY}'); + expect(state.protocol).toBe('openai-chat'); expect(state.models[0]).toEqual({ row: state.models[0].row, id: 'fast', name: 'Fast' }); expect(state.headers[0]).toEqual({ row: state.headers[0].row, key: 'X-Campus', value: '1' }); }); + test('prefills the protocol from a custom provider model', () => { + const state = providerToCustomFormState({ + id: 'responses-api', + options: { baseURL: 'https://api.example.com/v1' }, + models: [{ id: 'gpt', name: 'GPT', api: { npm: '@ai-sdk/openai' } }], + }); + + expect(state.protocol).toBe('openai-responses'); + }); + test('requires a config-layer source before treating a provider as editable custom', () => { const catalogLike = { id: 'openai', diff --git a/packages/ui/src/components/sections/providers/custom-provider-form.ts b/packages/ui/src/components/sections/providers/custom-provider-form.ts index 49178ece..355ee6db 100644 --- a/packages/ui/src/components/sections/providers/custom-provider-form.ts +++ b/packages/ui/src/components/sections/providers/custom-provider-form.ts @@ -1,10 +1,16 @@ /** - * Custom / Other OpenAI-compatible provider form helpers. + * Custom provider form helpers. * Mirrors OpenCode web UI validation and request construction so a provider * can be defined from Settings without code changes. */ -export const CUSTOM_PROVIDER_NPM = '@ai-sdk/openai-compatible'; +export const CUSTOM_PROVIDER_PROTOCOLS = { + 'openai-chat': '@ai-sdk/openai-compatible', + 'openai-responses': '@ai-sdk/openai', + 'anthropic-messages': '@ai-sdk/anthropic', +} as const; +export type CustomProviderProtocol = keyof typeof CUSTOM_PROVIDER_PROTOCOLS; +export type CustomProviderNpm = (typeof CUSTOM_PROVIDER_PROTOCOLS)[CustomProviderProtocol]; export const CUSTOM_PROVIDER_ID = '__custom_provider__'; const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9-_]*$/; const BASE_URL_PATTERN = /^https?:\/\//; @@ -30,6 +36,7 @@ export type HeaderRow = { export type CustomProviderFormState = { providerID: string; name: string; + protocol: CustomProviderProtocol; baseURL: string; apiKey: string; models: ModelRow[]; @@ -54,7 +61,7 @@ export type HeaderFieldErrors = { }; export type CustomProviderConfig = { - npm: typeof CUSTOM_PROVIDER_NPM; + npm: CustomProviderNpm; name: string; env?: string[]; options: { @@ -120,12 +127,24 @@ export const createHeaderRow = (): HeaderRow => ({ export const createEmptyCustomProviderForm = (): CustomProviderFormState => ({ providerID: '', name: '', + protocol: 'openai-chat', baseURL: '', apiKey: '', models: [createModelRow()], headers: [createHeaderRow()], }); +function protocolFromNpm(npm: string | undefined): CustomProviderProtocol { + switch (npm) { + case '@ai-sdk/openai': + return 'openai-responses'; + case '@ai-sdk/anthropic': + return 'anthropic-messages'; + default: + return 'openai-chat'; + } +} + function parseEnvApiKey(apiKey: string): { env?: string; key?: string } { const trimmed = apiKey.trim(); if (!trimmed) { @@ -159,7 +178,7 @@ export function isCustomOpenAICompatibleProvider(provider: ProviderLikeForCustom const api = 'api' in model && model.api && typeof model.api === 'object' ? model.api as { npm?: unknown } : null; - return typeof api?.npm === 'string' && api.npm === CUSTOM_PROVIDER_NPM; + return typeof api?.npm === 'string' && new Set(Object.values(CUSTOM_PROVIDER_PROTOCOLS)).has(api.npm); }); } @@ -238,9 +257,14 @@ export function providerToCustomFormState(provider: ProviderLikeForCustomForm): ? provider.env.find((entry) => typeof entry === 'string' && entry.trim().length > 0)?.trim() : undefined; + const modelWithApi = modelEntries.find( + (model): model is { id?: string; name?: string; api?: { npm?: string } } => 'api' in model, + ); + return { providerID: provider.id, name: typeof provider.name === 'string' && provider.name.trim() ? provider.name : provider.id, + protocol: protocolFromNpm(modelWithApi?.api?.npm), baseURL, apiKey: envName ? `{env:${envName}}` : '', models, @@ -360,7 +384,7 @@ export function validateCustomProvider(input: ValidateCustomProviderInput): Vali name, apiKey: key, config: { - npm: CUSTOM_PROVIDER_NPM, + npm: CUSTOM_PROVIDER_PROTOCOLS[input.form.protocol], name, ...(env ? { env: [env] } : {}), options: { diff --git a/packages/ui/src/components/sections/providers/provider-oauth.test.ts b/packages/ui/src/components/sections/providers/provider-oauth.test.ts index 93f8e762..e5291b12 100644 --- a/packages/ui/src/components/sections/providers/provider-oauth.test.ts +++ b/packages/ui/src/components/sections/providers/provider-oauth.test.ts @@ -7,11 +7,19 @@ import { isPromptVisible, parseAuthPrompts, parseAuthorization, + shouldOpenAuthorizationUrl, visiblePrompts, type AuthPrompt, type ProviderOAuthTranslator, } from './provider-oauth'; +describe('shouldOpenAuthorizationUrl', () => { + test('lets Claude Code CLI own browser launch', () => { + expect(shouldOpenAuthorizationUrl('claude-code', 'https://docs.example')).toBe(false); + expect(shouldOpenAuthorizationUrl('github-copilot', 'https://github.com/login')).toBe(true); + }); +}); + /** Mirrors the github-copilot auth method shipped by OpenCode. */ const copilotPrompts = [ { diff --git a/packages/ui/src/components/sections/providers/provider-oauth.ts b/packages/ui/src/components/sections/providers/provider-oauth.ts index f85a8ef6..4e7f130f 100644 --- a/packages/ui/src/components/sections/providers/provider-oauth.ts +++ b/packages/ui/src/components/sections/providers/provider-oauth.ts @@ -29,6 +29,9 @@ export interface OAuthAuthorization { userCode?: string; } +export const shouldOpenAuthorizationUrl = (providerId: string, url?: string): boolean => + Boolean(url) && providerId !== 'claude-code'; + export interface AuthPromptOption { label: string; value: string; diff --git a/packages/ui/src/components/sections/providers/providerAuth.ts b/packages/ui/src/components/sections/providers/providerAuth.ts index 18ca4a9c..ed6561b6 100644 --- a/packages/ui/src/components/sections/providers/providerAuth.ts +++ b/packages/ui/src/components/sections/providers/providerAuth.ts @@ -57,3 +57,6 @@ export const getOAuthAuthMethods = (methods: AuthMethod[]): OAuthAuthMethodEntry methods .map((method, methodIndex) => ({ method, methodIndex })) .filter(({ method }) => normalizeAuthType(method) === 'oauth'); + +export const requiresOpenCodeRestartAfterOAuth = (providerId: string): boolean => + providerId !== 'claude-code'; diff --git a/packages/ui/src/components/sections/providers/providerAvailability.ts b/packages/ui/src/components/sections/providers/providerAvailability.ts index ea6f0386..c2eabab4 100644 --- a/packages/ui/src/components/sections/providers/providerAvailability.ts +++ b/packages/ui/src/components/sections/providers/providerAvailability.ts @@ -1 +1,7 @@ export const shouldLoadAvailableProviders = (isAddMode: boolean): boolean => isAddMode; + +export const requiresProviderAuth = ( + sourcesLoaded: boolean, + hasCredentials: boolean, + isConfigDefinedCustomProvider: boolean, +): boolean => sourcesLoaded && !hasCredentials && !isConfigDefinedCustomProvider; diff --git a/packages/ui/src/components/sections/shared/SettingsProjectSelector.tsx b/packages/ui/src/components/sections/shared/SettingsProjectSelector.tsx index 709d5c50..9acbd7b0 100644 --- a/packages/ui/src/components/sections/shared/SettingsProjectSelector.tsx +++ b/packages/ui/src/components/sections/shared/SettingsProjectSelector.tsx @@ -12,9 +12,7 @@ import { isVSCodeRuntime } from '@/lib/desktop'; import { cn } from '@/lib/utils'; import { useI18n } from '@/lib/i18n'; -const formatProjectLabel = (label: string): string => { - return label.replace(/[-_]/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()); -}; +const formatProjectLabel = (label: string): string => label.trim(); export const SettingsProjectSelector: React.FC<{ className?: string }> = ({ className }) => { const { t } = useI18n(); diff --git a/packages/ui/src/components/sections/skills/SkillsSidebar.tsx b/packages/ui/src/components/sections/skills/SkillsSidebar.tsx index f440b9a5..18042671 100644 --- a/packages/ui/src/components/sections/skills/SkillsSidebar.tsx +++ b/packages/ui/src/components/sections/skills/SkillsSidebar.tsx @@ -439,12 +439,6 @@ const SkillListItem: React.FC = ({ }) => { const { t } = useI18n(); const isMobile = isMobileDeviceViaCSS(); - const sourceLabel = skill.source === 'claude' - ? t('settings.skills.sidebar.badge.claude') - : skill.source === 'agents' - ? t('settings.skills.sidebar.badge.agents') - : t('settings.skills.sidebar.badge.opencode'); - const badgeClassName = 'typography-micro text-muted-foreground bg-[var(--surface-muted)] px-1 rounded flex-shrink-0 leading-none pb-px border border-[var(--interactive-border)]/50'; const isBuiltIn = isBuiltInSkill(skill); const canRename = isRenamableSkill(skill); const [isContextMenuOpen, setIsContextMenuOpen] = React.useState(false); @@ -479,10 +473,6 @@ const SkillListItem: React.FC = ({ {skill.name} - - {skill.scope} - - {sourceLabel} diff --git a/packages/ui/src/components/sections/skills/catalog/InstallSkillDialog.tsx b/packages/ui/src/components/sections/skills/catalog/InstallSkillDialog.tsx index 60b7a0cf..802bd3f3 100644 --- a/packages/ui/src/components/sections/skills/catalog/InstallSkillDialog.tsx +++ b/packages/ui/src/components/sections/skills/catalog/InstallSkillDialog.tsx @@ -127,24 +127,13 @@ export const InstallSkillDialog: React.FC = ({ open, on directoryOverride?: string | null; conflictDecisions?: Record; }) => { - // Build selection with clawdhub metadata if present - const selection: { skillDir: string; clawdhub?: { slug: string; version: string } } = { - skillDir: request.skillDir, - }; - if (item?.clawdhub) { - selection.clawdhub = { - slug: item.clawdhub.slug, - version: item.clawdhub.version, - }; - } - const result = await installSkills({ source: request.source, subpath: request.subpath, gitIdentityId: item?.gitIdentityId, scope: request.scope, targetSource: request.targetSource, - selections: [selection], + selections: [{ skillDir: request.skillDir }], conflictPolicy: 'prompt', conflictDecisions: request.conflictDecisions, }, { directory: request.directoryOverride ?? null }); diff --git a/packages/ui/src/components/sections/skills/catalog/SkillsCatalogPage.tsx b/packages/ui/src/components/sections/skills/catalog/SkillsCatalogPage.tsx index 26218d76..621aa2fa 100644 --- a/packages/ui/src/components/sections/skills/catalog/SkillsCatalogPage.tsx +++ b/packages/ui/src/components/sections/skills/catalog/SkillsCatalogPage.tsx @@ -4,11 +4,7 @@ import { runtimeFetch } from '@/lib/runtime-fetch'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { SettingsPageLayout } from '@/components/sections/shared/SettingsPageLayout'; -import { - SettingsSection, - SETTINGS_SELECT_SIZE, - SETTINGS_SELECT_TRIGGER_CLASS, -} from '@/components/sections/shared/SettingsSection'; +import { SettingsSection } from '@/components/sections/shared/SettingsSection'; import { SortableTabsStrip } from '@/components/ui/sortable-tabs-strip'; import { Dialog, @@ -18,24 +14,16 @@ import { DialogHeader, DialogTitle, } from '@/components/ui/dialog'; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select'; -import { Icon } from "@/components/icon/Icon"; +import { Icon } from '@/components/icon/Icon'; import { useSkillsCatalogStore } from '@/stores/useSkillsCatalogStore'; import { useShallow } from 'zustand/react/shallow'; import { cn } from '@/lib/utils'; -import type { SkillsCatalogItem } from '@/lib/api/types'; - +import type { SkillsCatalogItem, SkillsCatalogSource } from '@/lib/api/types'; import { getRegisteredRuntimeAPIs } from '@/contexts/runtimeAPIRegistry'; import { updateDesktopSettings } from '@/lib/persistence'; import type { DesktopSettings, SkillCatalogConfig } from '@/lib/desktop'; -import { useI18n } from '@/lib/i18n'; +import { getCurrentIntlLocale, useI18n } from '@/lib/i18n'; import { AddCatalogDialog } from './AddCatalogDialog'; import { InstallSkillDialog } from './InstallSkillDialog'; @@ -48,6 +36,71 @@ interface SkillsCatalogPageProps { showModeTabs?: boolean; } +const GITHUB_REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; + +const getRepoUrl = (source: string): string | null => { + const trimmed = source.trim(); + if (!GITHUB_REPO_PATTERN.test(trimmed)) { + return null; + } + return `https://github.com/${trimmed}`; +}; + +const getSkillUrl = (item: SkillsCatalogItem): string | null => { + const repoUrl = getRepoUrl(item.repoSource); + if (!repoUrl) { + return null; + } + const skillPath = [item.repoSubpath, item.skillDir].filter(Boolean).join('/'); + return skillPath ? `${repoUrl}/tree/HEAD/${skillPath}` : repoUrl; +}; + +let cachedStarsFormatter: { locale: string; formatter: Intl.NumberFormat } | null = null; + +const formatStars = (stars: number): string => { + const locale = getCurrentIntlLocale(); + if (!cachedStarsFormatter || cachedStarsFormatter.locale !== locale) { + cachedStarsFormatter = { locale, formatter: new Intl.NumberFormat(locale, { notation: 'compact' }) }; + } + return cachedStarsFormatter.formatter.format(stars); +}; + +type RelativeTimeKey = + | 'common.relative.justNow' + | 'common.relative.minutesAgoShort' + | 'common.relative.hoursAgoShort' + | 'common.relative.daysAgoShort' + | 'common.relative.weeksAgoShort' + | 'common.relative.yearsAgoShort'; + +const formatRelativeShort = (isoDate: string): { key: RelativeTimeKey; count: number } | null => { + const timestamp = Date.parse(isoDate); + if (Number.isNaN(timestamp)) { + return null; + } + const diffMs = Date.now() - timestamp; + if (diffMs < 60_000) { + return { key: 'common.relative.justNow', count: 0 }; + } + const minutes = Math.floor(diffMs / 60_000); + if (minutes < 60) { + return { key: 'common.relative.minutesAgoShort', count: minutes }; + } + const hours = Math.floor(minutes / 60); + if (hours < 24) { + return { key: 'common.relative.hoursAgoShort', count: hours }; + } + const days = Math.floor(hours / 24); + if (days < 7) { + return { key: 'common.relative.daysAgoShort', count: days }; + } + const weeks = Math.floor(days / 7); + if (weeks < 52) { + return { key: 'common.relative.weeksAgoShort', count: weeks }; + } + return { key: 'common.relative.yearsAgoShort', count: Math.floor(days / 365) }; +}; + const loadSettings = async (): Promise => { try { const runtimeSettings = getRegisteredRuntimeAPIs()?.settings; @@ -71,6 +124,67 @@ const loadSettings = async (): Promise => { } }; +const SourceCard: React.FC<{ + source: SkillsCatalogSource; + isActive: boolean; + isLoading: boolean; + skillsCount: number | null; + onSelect: () => void; + t: ReturnType['t']; +}> = ({ source, isActive, isLoading, skillsCount, onSelect, t }) => { + const stars = source.stars ?? null; + const updated = source.repoUpdatedAt ? formatRelativeShort(source.repoUpdatedAt) : null; + + return ( + + ); +}; + export const SkillsCatalogPage: React.FC = ({ mode, onModeChange, showModeTabs = true }) => { const { t } = useI18n(); const { @@ -80,12 +194,9 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo setSelectedSource, loadCatalog, loadSource, - loadMoreClawdHub, isLoadingCatalog, isLoadingSource, - isLoadingMore, loadedSourceIds, - clawdhubHasMoreBySource, lastCatalogError, } = useSkillsCatalogStore(useShallow((s) => ({ sources: s.sources, @@ -94,12 +205,9 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo setSelectedSource: s.setSelectedSource, loadCatalog: s.loadCatalog, loadSource: s.loadSource, - loadMoreClawdHub: s.loadMoreClawdHub, isLoadingCatalog: s.isLoadingCatalog, isLoadingSource: s.isLoadingSource, - isLoadingMore: s.isLoadingMore, loadedSourceIds: s.loadedSourceIds, - clawdhubHasMoreBySource: s.clawdhubHasMoreBySource, lastCatalogError: s.lastCatalogError, }))); @@ -109,43 +217,72 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo const [installItem, setInstallItem] = React.useState(null); const [isRemovingCatalog, setIsRemovingCatalog] = React.useState(false); const [isRemoveCatalogDialogOpen, setIsRemoveCatalogDialogOpen] = React.useState(false); + const searchInputRef = React.useRef(null); React.useEffect(() => { void loadCatalog(); }, [loadCatalog]); + // Load every source in the background so global search covers all of them. React.useEffect(() => { - if (!selectedSourceId) { + const unloaded = sources.filter((src) => !loadedSourceIds[src.id]); + if (unloaded.length === 0) { return; } - if (!loadedSourceIds[selectedSourceId]) { - void loadSource(selectedSourceId); + let cancelled = false; + const loadRest = async () => { + for (const src of unloaded) { + if (cancelled) { + return; + } + await loadSource(src.id); + } + }; + void loadRest(); + return () => { + cancelled = true; + }; + }, [sources, loadedSourceIds, loadSource]); + + React.useEffect(() => { + if (!selectedSourceId || loadedSourceIds[selectedSourceId]) { + return; } + void loadSource(selectedSourceId); }, [selectedSourceId, loadedSourceIds, loadSource]); - const items = React.useMemo(() => { - if (!selectedSourceId) return []; - return itemsBySource[selectedSourceId] || []; - }, [itemsBySource, selectedSourceId]); + React.useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { + e.preventDefault(); + searchInputRef.current?.focus(); + } + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, []); + + const isSearching = search.trim().length > 0; const filtered = React.useMemo(() => { const q = search.trim().toLowerCase(); - if (!q) return items; - return items.filter((item) => { - const name = item.skillName.toLowerCase(); - const desc = (item.description || '').toLowerCase(); - const fm = (item.frontmatterName || '').toLowerCase(); - return name.includes(q) || desc.includes(q) || fm.includes(q); - }); - }, [items, search]); + const matches = (item: SkillsCatalogItem) => + item.skillName.toLowerCase().includes(q) + || (item.description || '').toLowerCase().includes(q) + || (item.frontmatterName || '').toLowerCase().includes(q); + + if (isSearching) { + return sources.flatMap((src) => (itemsBySource[src.id] || []).filter(matches)); + } + if (!selectedSourceId) { + return []; + } + return itemsBySource[selectedSourceId] || []; + }, [sources, itemsBySource, selectedSourceId, search, isSearching]); const selectedSource = React.useMemo(() => sources.find((s) => s.id === selectedSourceId) || null, [sources, selectedSourceId]); const isCustomSource = Boolean(selectedSourceId && selectedSourceId.startsWith('custom:')); - const isClawdHubSource = selectedSource?.source === 'clawdhub:registry' || selectedSource?.sourceType === 'clawdhub'; - const hasMoreClawdHub = Boolean( - selectedSourceId && (clawdhubHasMoreBySource[selectedSourceId] ?? true) - ); const removeSelectedCatalog = async () => { if (!selectedSourceId || !isCustomSource) { @@ -165,6 +302,17 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo } }; + const listTitle = isSearching + ? t('settings.skills.catalog.page.list.searchTitle') + : (selectedSource?.label ?? ''); + + // The selected source has no items yet and a load is in flight — show the + // loading state instead of a stale list from the previously selected source. + const isSelectedSourceLoading = !isSearching + && selectedSourceId !== null + && !loadedSourceIds[selectedSourceId] + && (isLoadingSource || isLoadingCatalog); + return ( <> = ({ mode, onMo )} +

+ {t('settings.skills.catalog.page.subtitle')} +

- +
+
+ + setSearch(e.target.value)} + placeholder={t('settings.skills.catalog.page.searchAllPlaceholder')} + className={cn('h-8 pl-8 w-full', search && 'pr-8')} + /> + {search && ( + + )} +
+
-
- +
+ {sources.map((src) => ( + setSelectedSource(src.id)} + t={t} + /> + ))} - - - {isCustomSource && ( - - )} - - -
- -
-
- - setSearch(e.target.value)} - placeholder={t('settings.skills.catalog.shared.field.searchSkillsPlaceholder')} - className="h-7 pl-8 w-full sm:w-64" - /> -
- - {isLoadingCatalog - ? t('settings.skills.catalog.page.loading.catalog') - : t('settings.skills.catalog.page.foundCount', { count: filtered.length })} +
+ + + {t('settings.skills.catalog.page.source.addOwnTitle')} + + + {t('settings.skills.catalog.page.source.addOwnDescription')} + + + +
{lastCatalogError && ( @@ -286,21 +418,63 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo )} - {filtered.length === 0 && !isLoadingSource ? ( -
-

{t('settings.skills.catalog.page.empty.noSkillsTitle')}

-

{t('settings.skills.catalog.page.empty.noSkillsDescription')}

-
- ) : isLoadingSource ? ( +
+
+ + {listTitle} + + + {t('settings.skills.catalog.page.foundCount', { count: filtered.length })} + +
+
+ + {isCustomSource && !isSearching && ( + + )} +
+
+ + {isSelectedSourceLoading || (isLoadingSource && filtered.length === 0) ? (

{t('settings.skills.catalog.page.loading.skills')}

+ ) : filtered.length === 0 ? ( +
+

{t('settings.skills.catalog.page.empty.noSkillsTitle')}

+

{t('settings.skills.catalog.page.empty.noSkillsDescription')}

+
) : (
{filtered.map((item) => { const installed = item.installed?.isInstalled; const installedScope = item.installed?.scope; + const skillUrl = getSkillUrl(item); return (
@@ -326,24 +500,28 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo
{t('settings.skills.catalog.shared.noDescription')}
)} - {item.clawdhub && ( -
- {item.clawdhub.owner && ( - {t('settings.skills.catalog.page.byOwnerPrefix')} {item.clawdhub.owner} - )} - - - {item.clawdhub.downloads?.toLocaleString() ?? 0} - - {(item.clawdhub.stars ?? 0) > 0 && ( - - - {item.clawdhub.stars} - - )} - v{item.clawdhub.version} -
- )} +
+ {skillUrl ? ( + + + {item.repoSource} + + ) : ( + {item.repoSource} + )} + {item.skillDir && ( + <> + · + {item.skillDir} + + )} +
{item.warnings?.length ? (
@@ -352,37 +530,43 @@ export const SkillsCatalogPage: React.FC = ({ mode, onMo ) : null}
- +
+ {skillUrl && ( + + )} + {installed ? ( + + + + ) : ( + + )} +
); })} )} - {isClawdHubSource && hasMoreClawdHub && !isLoadingSource && filtered.length > 0 && ( -
- -
- )}
diff --git a/packages/ui/src/components/sections/usage/UsagePage.tsx b/packages/ui/src/components/sections/usage/UsagePage.tsx index 0dac1033..7e8e3ccc 100644 --- a/packages/ui/src/components/sections/usage/UsagePage.tsx +++ b/packages/ui/src/components/sections/usage/UsagePage.tsx @@ -162,6 +162,11 @@ export const UsagePage: React.FC = () => { description={ isLoading ? ( {t('settings.usage.page.header.refreshing')} + ) : selectedResult?.planLabel ? ( + t('settings.usage.page.header.lastUpdatedWithPlan', { + plan: selectedResult.planLabel, + time: formatTime(lastUpdated, timeFormatPreference), + }) ) : ( t('settings.usage.page.header.lastUpdated', { time: formatTime(lastUpdated, timeFormatPreference) }) ) diff --git a/packages/ui/src/components/session/ArchiveAllDropdown.tsx b/packages/ui/src/components/session/ArchiveAllDropdown.tsx index 4e3bb808..6a76c3af 100644 --- a/packages/ui/src/components/session/ArchiveAllDropdown.tsx +++ b/packages/ui/src/components/session/ArchiveAllDropdown.tsx @@ -17,7 +17,7 @@ const ArchiveAllDropdown: React.FC = ({ onArchiveAll }) const { t } = useI18n(); return ( - +