Skip to content

Commit 8fe3190

Browse files
longtngoclaude
andcommitted
fix: four silent-data-loss paths, and make the only real gate run
**A commit could land on a shared repo's default branch after the user declined.** For an attached member repository `runGitActionWithToast` force-clears `featureBranch`, but the default-branch dialog still offered "Checkout feature branch & continue" as its primary button: it re-entered with the flag set, the flag was cleared, the prompt was suppressed, and the commit landed on the shared checkout's `main` anyway. The button is now offered only where it can be honoured. **The repository-ownership guard failed open.** `activeRepo` is null precisely while the repo list is empty — thread switch, reconnect, project refetch — and the guard skipped itself there, so a toast follow-up naming a member repo acted on the thread's own worktree. That is the redirection the comment above it forbids. **Selecting vLLM discarded every unrelated setting.** vLLM is `safetensors` and the model catalog holds only mlx/gguf, so choosing it produced `modelId: ""`, which `LocalLlmModelConfig` rejects — and because the panel patches `localLlm` as one whole object, the rejection dropped the entire patch with no error. Providers with no compatible model are no longer offered, and `onProviderChange` refuses such a switch as a backstop. **Applying a local-LLM preset appeared to do nothing, then undid itself.** The env-var table seeded state from props once; the card is keyed by instance id so it never remounted. The preset's variables were saved but invisible, and the next edit republished the stale draft over them. Re-seeding compares by value, not identity, so our own round-trip and a half-typed row never wipe the draft. **Git revisions reject a leading `-`.** `git diff --output=<path>` creates and truncates <path> while parsing arguments, before it fails (verified against git 2.55.0), so unvalidated refs made the read-only review RPCs a file-clobber primitive. Enforced in the schema so every call site inherits it. **The pre-push hook now runs the full gate.** `ci.yml` correctly lists `personal`, but every job asks for `blacksmith-*` runners that exist only in the upstream org, so jobs queue for 24h and cancel — 429 runs on this fork, zero successes, zero failures. The hook ran only typecheck+lint on the belief that CI covered the rest. It never has. AGENTS.md's contradicting claim is corrected. Also pins the turn-retention window: every case was written as RETAINED_TURN_ITEMS ± n, so the suite passed for any window and left the one number the module exists to choose unasserted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_017aHKjwZuipaALhwguxeRJe
1 parent e9f3dd6 commit 8fe3190

9 files changed

Lines changed: 220 additions & 47 deletions

File tree

‎.githooks/pre-push‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,21 @@
22
# Pre-push gate. Activated via `git config core.hooksPath .githooks`, set by the
33
# root package.json `prepare` script (no husky dependency).
44
#
5-
# Runs the FAST static gate (typecheck + lint). Thanks to the contract-typed
6-
# wsApi mock, typecheck now catches RPC/mock desync — the class of bug that once
7-
# rode an unrelated feature onto the trunk and sat red undetected. The full
8-
# unit + browser suites run in CI on push to `main`/`personal`.
5+
# Runs the FULL gate (typecheck + lint + test), because on this fork it is the
6+
# only gate that runs at all. CI is configured correctly — `ci.yml` does list
7+
# `personal` — but every job requests `blacksmith-*` runners, which are
8+
# provisioned for the upstream org and do not exist here. Jobs therefore queue
9+
# until GitHub's 24h timeout and are cancelled: at the time of writing, 429 runs
10+
# on this fork with zero successes and zero failures. An earlier version of this
11+
# hook ran only typecheck + lint on the belief that "the full unit suite runs in
12+
# CI"; that belief was false, so nothing ever executed the ~7.4k-test suite
13+
# automatically.
14+
#
15+
# If the fork's CI is ever pointed at runners that exist, this can go back to the
16+
# fast static gate.
917
#
10-
# To run the complete gate locally instead, use `pnpm verify`.
1118
# Bypass in a pinch with `git push --no-verify`.
1219
set -e
1320

14-
echo "pre-push: typecheck + lint (full suite runs in CI)…"
15-
pnpm run typecheck
16-
pnpm run lint
21+
echo "pre-push: typecheck + lint + test (nothing else runs this suite)…"
22+
pnpm run verify

‎AGENTS.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,11 @@ These rules override the ones above for this fork only.
118118
elsewhere in this file mean `personal` here.
119119
- **Run `pnpm verify` before merging to `personal`** — the full local gate (`typecheck` → `lint` →
120120
`test`). This is the one place the "do not run repo-wide checks, CI owns the full suite" rule
121-
above does not apply: CI only triggers on `main`, so nothing runs the suite for a `personal`
122-
merge except this gate.
121+
above does not apply, and the reason is stronger than it used to say: **CI does not run on this
122+
fork at all.** `ci.yml` does trigger on `personal`, but every job asks for `blacksmith-*`
123+
runners that only exist in the upstream org, so jobs queue for 24h and are cancelled — 429 runs,
124+
zero successes, zero failures. Local `pnpm verify` (and the pre-push hook that now runs it) is
125+
the entire safety net.
123126
- `pnpm test` runs each package's `unit` project. The `*.browser.tsx` files under `apps/web` are
124127
**not** wired into any test project right now (`apps/web/vite.config.ts` registers only
125128
`unitTestProject`), so no command runs them — don't assume they are covered.

‎apps/server/src/provider/Layers/turnItemRetention.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@ const makeTurns = (count: number) =>
66
Array.from({ length: count }, (_unused, index) => ({ items: [`item-${index}`] as Array<unknown> }));
77

88
describe("releaseOldTurnItems", () => {
9+
it("retains 20 turns", () => {
10+
// Every other case here is written as RETAINED_TURN_ITEMS ± n, which makes them all pass
11+
// for *any* window — 5, 1000, 1 — and so leaves the one number this module exists to
12+
// choose unasserted. The window trades replay fidelity against retained heap, so changing
13+
// it should require changing a test on purpose rather than sliding through green.
14+
expect(RETAINED_TURN_ITEMS).toBe(20);
15+
});
16+
917
it("keeps every entry, so the resume cursor's count and a revert's splice still work", () => {
1018
// This is the constraint that rules out simply capping the array: the
1119
// adapter reports `turns.length` as its resume cursor and reverts by

‎apps/web/src/components/GitActionsControl.tsx‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1334,7 +1334,11 @@ export default function GitActionsControl({
13341334
// raised earlier — a toast's follow-up, a confirmation the user left open
13351335
// — names the repository it belongs to, and is refused rather than
13361336
// silently redirected if the picker has moved since.
1337-
if (repoId !== undefined && activeRepo !== null && repoId !== activeRepo.id) {
1337+
// `activeRepo` is null precisely while the repo list is empty — a thread switch,
1338+
// a reconnect, a project refetch. Skipping the check there let a toast's follow-up
1339+
// fall through to `primaryGitCwd` and act on the thread's own worktree instead of
1340+
// the repository it names, which is the redirection the comment above forbids.
1341+
if (repoId !== undefined && repoId !== activeRepo?.id) {
13381342
const owner = workspaceRepos.find((repo) => repo.id === repoId);
13391343
toastManager.add(
13401344
stackedThreadToast({
@@ -2354,13 +2358,22 @@ export default function GitActionsControl({
23542358
>
23552359
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
23562360
</Button>
2357-
<Button
2358-
className="min-h-8 w-full max-w-full whitespace-normal py-1.5 leading-snug sm:min-h-7 sm:w-auto"
2359-
size="sm"
2360-
onClick={checkoutFeatureBranchAndContinuePendingAction}
2361-
>
2362-
Checkout feature branch & continue
2363-
</Button>
2361+
{/*
2362+
Offered only where it can be honoured. For an attached member repository
2363+
`runGitActionWithToast` force-clears `featureBranch` (members run on a branch
2364+
that already exists, cut inside `runStackedAction`), so this button would
2365+
suppress the prompt, drop the request, and commit to the shared checkout's
2366+
default branch anyway — silently doing the exact thing the user just declined.
2367+
*/}
2368+
{activeMemberRepo === null ? (
2369+
<Button
2370+
className="min-h-8 w-full max-w-full whitespace-normal py-1.5 leading-snug sm:min-h-7 sm:w-auto"
2371+
size="sm"
2372+
onClick={checkoutFeatureBranchAndContinuePendingAction}
2373+
>
2374+
Checkout feature branch & continue
2375+
</Button>
2376+
) : null}
23642377
</DialogFooter>
23652378
</DialogPopup>
23662379
</Dialog>

‎apps/web/src/components/settings/ProviderInstanceCard.tsx‎

Lines changed: 57 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from "lucide-react";
1313
import * as Arr from "effect/Array";
1414
import * as Result from "effect/Result";
15-
import { useState, type ReactNode } from "react";
15+
import { useRef, useState, type ReactNode } from "react";
1616
import {
1717
isProviderDriverKind,
1818
type ProviderInstanceConfig,
@@ -211,6 +211,40 @@ function LocalLlmPresetAction(props: {
211211
);
212212
}
213213

214+
/**
215+
* The environment these draft rows represent, or null while a row is still half-typed —
216+
* an incomplete row is not publishable, and must not read as "the user cleared it".
217+
*/
218+
function rowsToEnvironment(
219+
rows: ReadonlyArray<EnvironmentDraftRow>,
220+
): ProviderInstanceEnvironmentVariable[] | null {
221+
const published: ProviderInstanceEnvironmentVariable[] = [];
222+
for (const row of rows) {
223+
const name = row.name.trim();
224+
if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
225+
if (
226+
name.length > 0 ||
227+
row.value.length > 0 ||
228+
row.sensitive !== true ||
229+
row.valueRedacted !== undefined
230+
) {
231+
return null;
232+
}
233+
continue;
234+
}
235+
const { id: _id, ...rest } = row;
236+
published.push({ ...rest, name });
237+
}
238+
return published;
239+
}
240+
241+
/** Order-sensitive value identity, so an equal environment rebuilt as a new array compares equal. */
242+
function environmentKey(environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>): string {
243+
return JSON.stringify(
244+
environment.map((v) => [v.name, v.value, v.sensitive === true, v.valueRedacted === true]),
245+
);
246+
}
247+
214248
function ProviderEnvironmentSection(props: {
215249
readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
216250
readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
@@ -219,25 +253,29 @@ function ProviderEnvironmentSection(props: {
219253
props.environment.map(makeEnvironmentDraftRow),
220254
);
221255

222-
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
223-
const published: ProviderInstanceEnvironmentVariable[] = [];
224-
for (const row of nextRows) {
225-
const name = row.name.trim();
226-
if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
227-
if (
228-
name.length > 0 ||
229-
row.value.length > 0 ||
230-
row.sensitive !== true ||
231-
row.valueRedacted !== undefined
232-
) {
233-
return;
234-
}
235-
continue;
236-
}
237-
const { id: _id, ...rest } = row;
238-
published.push({ ...rest, name });
256+
// Re-seed when the instance's environment changes underneath us — "Apply a local-LLM
257+
// preset" writes through `onApply`, and this card is keyed by instance id so it does not
258+
// remount. Without this the table kept rendering the pre-preset rows, and the next edit
259+
// republished that stale draft, deleting the variables the preset had just added.
260+
//
261+
// Compared by VALUE, not identity: our own publish round-trips through the parent and
262+
// comes back as a fresh array, which would re-seed on every keystroke and discard a
263+
// half-typed row. A row that is still incomplete is dropped from `publishRows` output, so
264+
// it does not register as a difference either — only a genuine external write does.
265+
const draftEnvironment = rowsToEnvironment(rows);
266+
const incoming = environmentKey(props.environment);
267+
const seededRef = useRef(incoming);
268+
if (seededRef.current !== incoming) {
269+
seededRef.current = incoming;
270+
// A half-typed row (null) means the user is mid-edit; leave their draft alone.
271+
if (draftEnvironment !== null && environmentKey(draftEnvironment) !== incoming) {
272+
setRows(props.environment.map(makeEnvironmentDraftRow));
239273
}
240-
props.onChange(published);
274+
}
275+
276+
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
277+
const published = rowsToEnvironment(nextRows);
278+
if (published) props.onChange(published);
241279
};
242280

243281
const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {

‎apps/web/src/components/settings/localLlm/modelConfig.logic.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { LocalLlmSettings } from "@t3tools/contracts";
22
import { describe, expect, it } from "vite-plus/test";
3+
import { LOCAL_LLM_PROVIDERS, compatibleModels } from "@t3tools/shared/localLlm";
34
import {
45
clampContext,
56
newModelConfig,
@@ -65,3 +66,34 @@ describe("onProviderChange / onModelChange", () => {
6566
expect(next.contextWindow).toBe(131072);
6667
});
6768
});
69+
70+
describe("providers with no compatible model", () => {
71+
const empty = settings();
72+
73+
it("keeps a provider the catalog has no model for out of the picker", () => {
74+
// vllm is `format: "safetensors"` and the model catalog carries only mlx/gguf, so
75+
// offering it can only produce `modelId: ""` — which the contract rejects, taking the
76+
// entire localLlm patch down with it.
77+
const ids = visibleProviders(empty).map((p) => p.id);
78+
for (const id of ids) {
79+
expect(compatibleModels(id).length).toBeGreaterThan(0);
80+
}
81+
});
82+
83+
it("still lists the provider a config is already on", () => {
84+
const withNone = LOCAL_LLM_PROVIDERS.find((p) => compatibleModels(p.id).length === 0);
85+
if (!withNone) return;
86+
expect(visibleProviders(empty, withNone.id).some((p) => p.id === withNone.id)).toBe(true);
87+
});
88+
89+
it("refuses to switch to a provider that would produce an empty modelId", () => {
90+
const withNone = LOCAL_LLM_PROVIDERS.find((p) => compatibleModels(p.id).length === 0);
91+
if (!withNone) return;
92+
const start = newModelConfig(empty);
93+
expect(onProviderChange(start, withNone.id)).toEqual(start);
94+
});
95+
96+
it("never builds a fresh config with an empty modelId", () => {
97+
expect(newModelConfig(empty).modelId).not.toBe("");
98+
});
99+
});

‎apps/web/src/components/settings/localLlm/modelConfig.logic.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,16 @@ export function visibleProviders(
2323
currentProviderId?: string,
2424
): ProviderCatalogEntry[] {
2525
return LOCAL_LLM_PROVIDERS.filter(
26-
(p) => providerVisible(settings, p.id) || p.id === currentProviderId,
26+
(p) =>
27+
// A provider the model catalog has nothing compatible for cannot produce a valid
28+
// config: it yields `modelId: ""`, which `LocalLlmModelConfig` rejects. Because the
29+
// panel saves `localLlm` as one whole object, that rejection discards the entire
30+
// settings patch — every unrelated edit with it — and reports nothing. Several
31+
// catalog providers (vllm, llamacpp, lmstudio, ollama) are in exactly that state.
32+
// The current provider stays listed regardless, so an existing config never
33+
// silently loses its own selection.
34+
(compatibleModels(p.id).length > 0 && providerVisible(settings, p.id)) ||
35+
p.id === currentProviderId,
2736
);
2837
}
2938

@@ -79,10 +88,13 @@ export function onProviderChange(
7988
providerId: string,
8089
): LocalLlmModelConfig {
8190
const model = compatibleModels(providerId)[0];
82-
const modelId = model?.id ?? "";
83-
const contextWindow = model
84-
? clampContext(config.contextWindow ?? model.maxContext, modelId)
85-
: undefined;
91+
// No compatible model means the only config we could build is invalid (`modelId: ""`),
92+
// and saving it would discard the whole `localLlm` patch. Refuse the switch instead:
93+
// `visibleProviders` already keeps such providers out of the picker, so this is the
94+
// backstop for a caller that bypasses it.
95+
if (!model) return config;
96+
const modelId = model.id;
97+
const contextWindow = clampContext(config.contextWindow ?? model.maxContext, modelId);
8698
return { ...config, providerId, modelId, contextWindow };
8799
}
88100

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import * as Schema from "effect/Schema";
3+
4+
import { ReviewDiffFileContentsInput, ReviewDiffPreviewInput } from "./review.ts";
5+
6+
const decodePreview = Schema.decodeUnknownSync(ReviewDiffPreviewInput);
7+
const decodeFileContents = Schema.decodeUnknownSync(ReviewDiffFileContentsInput);
8+
9+
const fileContents = (overrides: Record<string, unknown>) => ({
10+
cwd: "/repo",
11+
sourceKind: "branch-range",
12+
changeType: "change",
13+
baseRef: "main",
14+
headRef: "HEAD",
15+
oldPath: "src/a.ts",
16+
newPath: "src/a.ts",
17+
...overrides,
18+
});
19+
20+
describe("review revision inputs", () => {
21+
it("accepts the revision shapes review actually sends", () => {
22+
expect(decodePreview({ cwd: "/repo", baseRef: "origin/main" }).baseRef).toBe("origin/main");
23+
for (const revision of ["HEAD", "HEAD~3", "v1.2.3", "abc1234", "feature/x"]) {
24+
expect(decodePreview({ cwd: "/repo", baseRef: revision }).baseRef).toBe(revision);
25+
}
26+
});
27+
28+
it("rejects an option-shaped revision, which git would parse as a flag", () => {
29+
// `git diff --output=<path>` creates and truncates <path> while parsing arguments —
30+
// before it fails — so an unvalidated ref turns these read-only RPCs into a file
31+
// clobber. Git will not create a ref beginning with "-", so nothing real is refused.
32+
expect(() => decodePreview({ cwd: "/repo", baseRef: "--output=/tmp/pwned" })).toThrow();
33+
expect(() => decodePreview({ cwd: "/repo", baseRef: "-o/tmp/pwned" })).toThrow();
34+
});
35+
36+
it("rejects option-shaped refs and paths on the file-contents input", () => {
37+
for (const field of ["baseRef", "headRef", "oldPath", "newPath"]) {
38+
expect(() => decodeFileContents(fileContents({ [field]: "--output=/tmp/pwned" }))).toThrow();
39+
}
40+
expect(decodeFileContents(fileContents({})).baseRef).toBe("main");
41+
});
42+
});

‎packages/contracts/src/review.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,27 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts";
33
import { GitCommandError } from "./git.ts";
44
import { VcsError } from "./vcs.ts";
55

6+
/**
7+
* A git revision supplied by a client.
8+
*
9+
* Refs reach `git diff` / `git show` positionally, with no `--` separator, so an
10+
* option-shaped value is parsed as an option rather than a revision. That is not merely a
11+
* bad diff: `git diff --output=<path>` creates and truncates `<path>` while parsing its
12+
* arguments, before it ever fails — turning read-only-looking review RPCs into a file
13+
* clobber primitive anywhere the server can write. A real ref can never begin with `-`
14+
* (git refuses to create one), so rejecting the shape costs nothing legitimate.
15+
*/
16+
const GitRevision = TrimmedNonEmptyString.pipe(
17+
Schema.check(
18+
Schema.makeFilter(
19+
(value: string) => !value.startsWith("-") || "a git revision cannot begin with '-'",
20+
),
21+
),
22+
);
23+
624
export const ReviewDiffPreviewInput = Schema.Struct({
725
cwd: TrimmedNonEmptyString,
8-
baseRef: Schema.optional(TrimmedNonEmptyString),
26+
baseRef: Schema.optional(GitRevision),
927
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
1028
});
1129
export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
@@ -29,10 +47,11 @@ export const ReviewDiffFileContentsInput = Schema.Struct({
2947
cwd: TrimmedNonEmptyString,
3048
sourceKind: ReviewDiffPreviewSourceKind,
3149
changeType: Schema.Literals(["change", "rename-pure", "rename-changed", "new", "deleted"]),
32-
baseRef: Schema.NullOr(TrimmedNonEmptyString),
33-
headRef: Schema.NullOr(TrimmedNonEmptyString),
34-
oldPath: TrimmedNonEmptyString,
35-
newPath: TrimmedNonEmptyString,
50+
baseRef: Schema.NullOr(GitRevision),
51+
headRef: Schema.NullOr(GitRevision),
52+
// Paths are interpolated as `<revision>:<path>`, so a leading `-` is option-shaped there too.
53+
oldPath: GitRevision,
54+
newPath: GitRevision,
3655
});
3756
export type ReviewDiffFileContentsInput = typeof ReviewDiffFileContentsInput.Type;
3857

0 commit comments

Comments
 (0)