Skip to content

Fail Source lint on a duplicate TypeScript import binding - #8548

Merged
danielhanchen merged 17 commits into
mainfrom
fix/duplicate-hubmodelpicker-import
Sep 21, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
fix/duplicate-hubmodelpicker-import

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Adds a lint gate that fails on a duplicate TypeScript import binding, before tsc gets there.

The duplicate HubModelPicker import in model-selector.tsx is already fixed on main, twice over: #8534 and #8553 landed the same one-line removal within hours of each other. That is the argument for the gate. Both were found the same way, as a TS2300 inside the slowest job in the matrix, after a full frontend build had already burned its time. Two people independently paid that cost for one duplicated line.

So this PR no longer removes anything. Its diff is the gate and its wiring:

  • scripts/lint_no_duplicate_ts_imports.py parses import clauses and reports any binding declared twice in a file, covering default, namespace, named, aliased and type-only forms.
  • .github/workflows/lint-ci.yml runs it, with --self-test first so a broken matcher fails loudly rather than passing everything.

It scans every TypeScript project the frontend build actually compiles, not just src. npm run build is tsc -b, which builds tsconfig.json and its references tsconfig.app.json (src) and tsconfig.node.json (vite.config.ts); npm run typecheck adds tsconfig.test.json (tests). Scanning src alone left two of the three projects that can emit TS2300 unguarded.

The self-test carries ten cases, including the #8470 regression verbatim, so the check is pinned against the shape that actually broke the build.

danielhanchen and others added 2 commits August 12, 2026 12:11
#8470 added a second

    import { HubModelPicker, hasDownloadedModels } from "./model-selector/pickers";

to model-selector.tsx, seven lines below the one already there. tsc rejects it
with TS2300 Duplicate identifier, so npm run build fails, so the Build frontend
step fails, and every job that builds the frontend goes red behind it: Chat UI
Tests, GGUF inference smoke, Tool calling, Unsloth API and Auth, the wheel
build, the no-Visual-Studio install, and the rest. On main and on every open PR.

Nothing caught it earlier. eslint is not run in CI at all, and its config does
not enable no-duplicate-imports in any case, so the first sign was a tsc error
inside the slowest job in the matrix.

scripts/lint_no_duplicate_ts_imports.py is the cheap version of that check,
wired into Source lint next to the other safety nets: it scans the import
prologue of every committed .ts/.tsx file and reports any local binding name
introduced twice. No npm, no node, no type information. It parses the four
binding forms (default, namespace, named, aliased), treats import type as
binding the same way a value import does, and skips side-effect imports, which
bind nothing. Two imports of the same module under different names stay legal,
so the module path is not what it compares.

--self-test covers ten cases including this regression verbatim, and reverting
the one-line fix turns the scan red on exactly the two names.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 06daf4808a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint_no_duplicate_ts_imports.py Outdated
# broken across lines -- which is how prettier formats anything long, and how
# the #8470 duplicate was formatted -- is still one match.
_IMPORT = re.compile(
r"^[ \t]*import[ \t]+(?P<clause>[^;'\"]*?)[ \t]*from[ \t]*['\"][^'\"]+['\"]",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore imports inside comments and template literals

When a TS/TSX file contains a block comment or multiline template with a line such as import { Widget } from "example";, this multiline regex treats that text as a real declaration because it does not account for lexical context. If the file later genuinely imports Widget, duplicates_in reports a duplicate and the new Source lint step hard-fails even though the TypeScript source is valid. Strip or tokenize comments and strings before matching import declarations.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving the matcher as is. Zero hits across all 1398 compiled .ts/.tsx files - I ran the regex over every one and checked each match's lexical context - and the ^[ \t]*import ... from "..." anchor already skips JSDoc ( * import ...) and single-line strings. The suggested pre-pass is the riskier change: src/components/assistant-ui/message-html-artifacts.tsx has a line comment containing ```html, so a backtick-aware stripper decides the import prologue is inside a template literal and drops four real imports. That trades a hypothetical false positive for a false negative in a file we have.

Comment on lines +92 to +93
elif piece.isidentifier():
names.append(piece)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recognize dollar-prefixed default import bindings

JavaScript and TypeScript binding identifiers may contain $, but Python's str.isidentifier() rejects it. Consequently, valid declarations such as import $client from "a"; and import $client from "b"; produce TS2300 while _bindings records neither name and this guard reports the file as clean. Parse the JavaScript identifier grammar rather than using Python's identifier predicate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct about isidentifier(), but leaving it. The direction is a miss rather than a false hard-fail, and tsc -b is still the authority this step only front-runs. It is also narrower than described - _bindings only applies the predicate to the default/namespace part, so import { $a } from "m" already works - and there are no import $... declarations under studio/ at all.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2040b2a7e4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +115 to +116
if path.suffix not in (".ts", ".tsx"):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include .mts files in the TypeScript scan

When a source file under src uses TypeScript's standard .mts extension, tsconfig.app.json includes it and tsc -b reports duplicate import bindings, but this suffix filter silently skips the file. A duplicate import in such a module therefore passes the new fast gate and still breaks the frontend build; include all TypeScript extensions accepted by the project rather than only .ts and .tsx.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this. There are zero .mts/.cts files under studio/frontend (checked over the whole tree, not just src), and the direction of the gap is a miss rather than a false hard-fail: tsc -b still reports TS2300 and stays the authority this step only front-runs. Same call as 3766298322 last round.


def duplicates_in(source: str) -> list[tuple[int, str]]:
"""(line number, name) for every binding this file introduces twice."""
seen: dict[str, int] = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track import bindings by TypeScript scope

When a scanned .d.ts file contains separate ambient module declarations that each import the same local name, TypeScript treats those imports as bindings in distinct scopes and accepts the file, but this single file-wide seen map reports the second one as a duplicate. Since .d.ts files are included by the current suffix check and there are already declaration files under src, this can make Source lint hard-fail on valid declarations; compare bindings within their enclosing module scope rather than across the entire file.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed the construct does trip the matcher - a synthetic file with two declare module blocks each binding Foo reports a duplicate at line 5 - but it is not reachable in this tree. Of the 1398 files the gate scans, three contain declare module (src/asset-queries.d.ts, src/app/router.tsx, src/app/routes/__root.tsx) and none of them declares an import inside the block; the scan is clean at 0 findings today. Brace-tracking a scope stack is exactly the kind of pre-pass that made the template-literal suggestion riskier than the gap it closed, and if someone ever writes the ambient form the failure is a loud lint red with the file and name in it, not a silent miss.

Comment thread scripts/lint_no_duplicate_ts_imports.py Outdated
# broken across lines -- which is how prettier formats anything long, and how
# the #8470 duplicate was formatted -- is still one match.
_IMPORT = re.compile(
r"^[ \t]*import[ \t]+(?P<clause>[^;'\"]*?)[ \t]*from[ \t]*['\"][^'\"]+['\"]",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse string-named import specifiers

When a module uses the valid form import { "export-name" as Local } from "m", the quote inside the clause prevents this regex from matching the declaration at all. If another import in the file also binds Local, TypeScript 5.9 reports TS2300 but this guard records only the other declaration and exits cleanly; allow quoted imported names while still extracting the alias that creates the local binding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this. import { "export-name" as Local } from "m" does not occur anywhere under studio/, and the consequence is again a miss, not a hard-fail on valid code, with tsc -b behind it. Widening the clause pattern to allow quotes also weakens the anchor that currently keeps JSDoc and single-line strings out.

The gate only looked at studio/frontend/src, but npm run build is tsc -b and
npm run typecheck adds tsc -p tsconfig.test.json, so vite.config.ts
(tsconfig.node.json) and tests (tsconfig.test.json) compile too. A duplicate
import in either passed this step and still failed the frontend build, which
is the failure the step exists to catch first. Scan the frontend root instead;
node_modules, dist and build are already skipped, and the 1398 files it now
covers are clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f53f739c9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +95 to +98
if piece.startswith("*"):
parts = piece.split()
names.append(parts[-1]) # `* as ns`
elif piece.isidentifier():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle import defer namespace bindings

When a scanned file uses TypeScript 5.9's valid deferred-import form, such as import defer * as Foo from "a", the remaining clause starts with defer rather than *, so _bindings records no namespace binding. Two deferred imports binding Foo therefore pass this fast gate even though the repository's TypeScript 5.9 compiler reports TS2300 during the later frontend build; strip the defer phase modifier before parsing the namespace clause.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this. There is no import defer anywhere under studio/, and a deferred import that slips past this step is a miss that tsc -b still catches. Not worth a phase-modifier parser in a regex front-runner.

@danielhanchen danielhanchen changed the title Remove the duplicate import that fails every frontend build Fail Source lint on a duplicate TypeScript import binding Aug 12, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48bf57042e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# tsconfig.app.json (`src`), tsconfig.node.json (`vite.config.ts`) and
# tsconfig.test.json (`tests`). Scanning only `src` leaves the other two able to
# red the frontend build with the very error this step exists to catch first.
DEFAULT_SCAN_DIR = REPO_ROOT / "studio" / "frontend"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the packaged Pi TypeScript extension in the scan

Fresh evidence beyond the earlier frontend-project coverage fix is unsloth_cli/pi_subagent.ts: it is shipped as package data in pyproject.toml:51 and passed to Pi as an executable extension in unsloth_cli/commands/start.py:4850-4863, but this default root excludes it. A duplicate binding in that production TypeScript file therefore passes Source lint and can make --as-subagent fail when Pi loads the extension, without the later frontend tsc build acting as a backstop; scan the repository root with the existing exclusions or include this file explicitly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this. The facts are right - unsloth_cli/pi_subagent.ts is package data (pyproject.toml:51) and is handed to Pi at start.py:120 - but this is a scope change rather than a defect in what the gate does. The step exists to front-run tsc -b on the frontend build so a TS2300 does not cost the slowest job in the matrix; pi_subagent.ts is compiled by nobody here, so folding it in means the gate is no longer "the thing the build would have caught, caught sooner", and scanning the repository root pulls in every unrelated .ts under it. Worth its own change with its own reasoning if Pi extensions should be linted, not a widening of this one.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 635bb4a388

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The inline and clause-level `type` modifiers were stripped with a literal
"type " prefix test, so a specifier wrapped as `type\n  Foo` kept its modifier
and `piece.split()[0]` recorded `type` as the binding. Two of those in one file
report `type` as a duplicate and fail Source lint on a file tsc compiles
cleanly, and a wrapped modifier also hid a real duplicate, since the binding
recorded was never the imported name.

tsc 7.0.2 accepts all three shapes (`type` + newline, `type` + tab, and
`import type` + newline before the brace) with exit 0 and no TS2300; any
whitespace is legal after the modifier.

Both strips now go through one `^type\s+` pattern. Three self-test cases cover
the two false positives and the missed duplicate.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 883a07562b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The scan read the raw file, so a test fixture holding TypeScript inside a
template literal was read as imports of the enclosing file. Two fixtures
quoting the same module then looked like a duplicate, and on today's main
the gate reports six of these across two frontend test files, all of them
source held as data. A gate that fails CI on code tsc accepts is worse than
no gate, so this had to be fixed before the gate could land.

Comment and string bodies are blanked before the scan, with the character
count and every newline kept so the reported line numbers still point at the
real source. Module specifiers survive as whitespace inside their quotes and
still match, so the masking cannot hide a genuine import. A block comment is
covered for the same reason: commented-out imports are not imports.

Five self-test cases, including a real duplicate sitting after a fixture, a
backtick inside an ordinary string, and an escaped backtick that does not
close its template. 21 cases in total, and the live tree is clean across
2238 files.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T09:59:35.349851Z 4309007 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The masker left regex literals out and the comment said that could only
miss a duplicate. That was wrong. `const BACKTICK = /`/g;` is real code in
studio/frontend/src/lib/release-notes-preview.ts, and an unrecognised
backtick there pairs with the opener of the next real template, so the
masking lands on the gap between them and leaves the fixture exposed. The
gate then invents a duplicate on a file tsc accepts, which is the failure
direction that matters for something wired into an unconditional lint gate.

Telling a regex from a division needs the previous token, since `/` is
both. The usual test: after a value, so an identifier, a literal or a
closing bracket, it divides; anywhere else it opens a regex, with the
operator keywords that end in identifier characters listed by name. A
character class can hold an unescaped `/`, so the scan tracks `[...]`, and
a regex that reaches a newline is treated as a division after all rather
than masking to the end of the file.

Six more self-test cases covering both directions, 27 in total. The live
tree stays clean across 2238 files and a real duplicate in real code is
still caught.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A component can render a code sample as element text:

    export function Sample() {
      return (
        <pre>
    import Widget from "a";
        </pre>
      );
    }

TypeScript reads those lines as JSX text and accepts the file, and they are
unindented because indentation would show up in what the page renders, so
anchoring to the start of the line does not separate them from real imports.

An import declaration is only legal at the top level of a module, so what
does separate them is that these sit inside the function body and the
parenthesised return. Brackets are counted over the masked source, where
strings, comments and regexes are already gone, and a match inside any
bracket is skipped.

This is not JSX recognition and does not pretend to be. It declines to read
a declaration anywhere the grammar would not allow one, which covers the
reported case and leaves real imports untouched.

Two more self-test cases, 29 in total: the sample above, and a real
duplicate sitting after such a component. Live tree clean across 2238 files.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two more ways to be read as an import while tsc reads something else.

Bracket depth does not separate a module-level JSX initializer written
without wrapping parentheses, because JSX tags are not brackets:
`const sample = <pre>` followed by import-shaped text leaves the depth at
zero. What does separate it is that those lines start no statement. The
character before a real import, once trivia is skipped, is the start of the
file, the end of a previous statement, or the closing quote of a module
specifier, which is how the previous import ends in a file that omits
semicolons. JSX text is preceded by `>`, which ends nothing.

Measured against the tree before adopting it: of the 9801 imports the
scanner accepts today, that rule keeps 9801 and rejects none.

A regex after an unbraced control head, `if (ok) /`/.test(text);`, was read
as a division because of the closing paren. A control statement's
parentheses produce no value, so the scan now walks back to the matching
`(` and reads the word in front of it.

Five more self-test cases, 34 in total, including a division after a call,
a file that omits semicolons, and an import after a function declaration,
so the new rule cannot be satisfied by quietly ignoring more. Live tree
clean across 2238 files.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Seven times now a whole-file scan has been reported for calling valid
TypeScript a duplicate: source quoted inside a test fixture, a backtick
inside a regex pairing with a later template, a code sample rendered as JSX
text, a module-level JSX initializer with no wrapping parentheses, a nested
template, and JSX text after an expression container. Each fix was correct
and the next hole was already there. The shape of the problem is that
reading TypeScript as raw text needs a lexer, and half a lexer keeps finding
new ways to be wrong in the direction that stops other people's work, since
this gate runs unconditionally on Source lint.

So the scan is bounded instead. It reads the import prologue, meaning the
run of imports, comments and directives at the top of the file, and stops at
the first statement that is not one. A prologue cannot contain a template, a
regex or JSX, so nothing that merely looks like an import can appear in it,
and all seven become impossible rather than handled. The masking, the regex
recogniser, the bracket-depth rule and the statement-boundary rule all go
with it: 362 lines removed, 125 added.

The cost is stated rather than hidden. An import written after other
top-level code is not read, so a duplicate involving one is missed: 611 of
9801 import declarations here, across 19 files. That is a false negative,
which leaves the build where it was before this check existed and which tsc
still catches. A false positive fails CI on correct code. Given the choice,
this misses those.

19 self-test cases. The six false positives above are kept as cases, so a
later change that widens the scan fails here rather than in CI, and so is
the stated cost, so it stays a decision rather than a surprise. The #8470
regression is still caught verbatim, the live tree is clean across 2238
files, and a real duplicate planted in a file full of fixtures is still
reported on the right line.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 4309007c22

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 83fb493 into main Sep 21, 2026
14 of 16 checks passed
@danielhanchen
danielhanchen deleted the fix/duplicate-hubmodelpicker-import branch September 21, 2026 10:20
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…8548)

* Remove the duplicate import that fails every frontend build

unslothai#8470 added a second

    import { HubModelPicker, hasDownloadedModels } from "./model-selector/pickers";

to model-selector.tsx, seven lines below the one already there. tsc rejects it
with TS2300 Duplicate identifier, so npm run build fails, so the Build frontend
step fails, and every job that builds the frontend goes red behind it: Chat UI
Tests, GGUF inference smoke, Tool calling, Unsloth API and Auth, the wheel
build, the no-Visual-Studio install, and the rest. On main and on every open PR.

Nothing caught it earlier. eslint is not run in CI at all, and its config does
not enable no-duplicate-imports in any case, so the first sign was a tsc error
inside the slowest job in the matrix.

scripts/lint_no_duplicate_ts_imports.py is the cheap version of that check,
wired into Source lint next to the other safety nets: it scans the import
prologue of every committed .ts/.tsx file and reports any local binding name
introduced twice. No npm, no node, no type information. It parses the four
binding forms (default, namespace, named, aliased), treats import type as
binding the same way a value import does, and skips side-effect imports, which
bind nothing. Two imports of the same module under different names stay legal,
so the module path is not what it compares.

--self-test covers ten cases including this regression verbatim, and reverting
the one-line fix turns the scan red on exactly the two names.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scan every TypeScript project the frontend build compiles

The gate only looked at studio/frontend/src, but npm run build is tsc -b and
npm run typecheck adds tsc -p tsconfig.test.json, so vite.config.ts
(tsconfig.node.json) and tests (tsconfig.test.json) compile too. A duplicate
import in either passed this step and still failed the frontend build, which
is the failure the step exists to catch first. Scan the frontend root instead;
node_modules, dist and build are already skipped, and the 1398 files it now
covers are clean.

* Drop comments from an import clause before reading its bindings

* Read a wrapped alias and a relative scan path correctly

* Trim the duplicate-import lint comments to the rationale

* Trim the lint step comments in the workflow

* Read a type modifier followed by any whitespace

The inline and clause-level `type` modifiers were stripped with a literal
"type " prefix test, so a specifier wrapped as `type\n  Foo` kept its modifier
and `piece.split()[0]` recorded `type` as the binding. Two of those in one file
report `type` as a duplicate and fail Source lint on a file tsc compiles
cleanly, and a wrapped modifier also hid a real duplicate, since the binding
recorded was never the imported name.

tsc 7.0.2 accepts all three shapes (`type` + newline, `type` + tab, and
`import type` + newline before the brace) with exit 0 and no TS2300; any
whitespace is legal after the modifier.

Both strips now go through one `^type\s+` pattern. Three self-test cases cover
the two false positives and the missed duplicate.

* Do not read a quoted TypeScript fixture as an import

The scan read the raw file, so a test fixture holding TypeScript inside a
template literal was read as imports of the enclosing file. Two fixtures
quoting the same module then looked like a duplicate, and on today's main
the gate reports six of these across two frontend test files, all of them
source held as data. A gate that fails CI on code tsc accepts is worse than
no gate, so this had to be fixed before the gate could land.

Comment and string bodies are blanked before the scan, with the character
count and every newline kept so the reported line numbers still point at the
real source. Module specifiers survive as whitespace inside their quotes and
still match, so the masking cannot hide a genuine import. A block comment is
covered for the same reason: commented-out imports are not imports.

Five self-test cases, including a real duplicate sitting after a fixture, a
backtick inside an ordinary string, and an escaped backtick that does not
close its template. 21 cases in total, and the live tree is clean across
2238 files.

* Recognise regex literals, which did not fail open as claimed

The masker left regex literals out and the comment said that could only
miss a duplicate. That was wrong. `const BACKTICK = /`/g;` is real code in
studio/frontend/src/lib/release-notes-preview.ts, and an unrecognised
backtick there pairs with the opener of the next real template, so the
masking lands on the gap between them and leaves the fixture exposed. The
gate then invents a duplicate on a file tsc accepts, which is the failure
direction that matters for something wired into an unconditional lint gate.

Telling a regex from a division needs the previous token, since `/` is
both. The usual test: after a value, so an identifier, a literal or a
closing bracket, it divides; anywhere else it opens a regex, with the
operator keywords that end in identifier characters listed by name. A
character class can hold an unescaped `/`, so the scan tracks `[...]`, and
a regex that reaches a newline is treated as a division after all rather
than masking to the end of the file.

Six more self-test cases covering both directions, 27 in total. The live
tree stays clean across 2238 files and a real duplicate in real code is
still caught.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not read a declaration where the language would not allow one

A component can render a code sample as element text:

    export function Sample() {
      return (
        <pre>
    import Widget from "a";
        </pre>
      );
    }

TypeScript reads those lines as JSX text and accepts the file, and they are
unindented because indentation would show up in what the page renders, so
anchoring to the start of the line does not separate them from real imports.

An import declaration is only legal at the top level of a module, so what
does separate them is that these sit inside the function body and the
parenthesised return. Brackets are counted over the masked source, where
strings, comments and regexes are already gone, and a match inside any
bracket is skipped.

This is not JSX recognition and does not pretend to be. It declines to read
a declaration anywhere the grammar would not allow one, which covers the
reported case and leaves real imports untouched.

Two more self-test cases, 29 in total: the sample above, and a real
duplicate sitting after such a component. Live tree clean across 2238 files.

* Require an import to start a statement, and read a control head's parens

Two more ways to be read as an import while tsc reads something else.

Bracket depth does not separate a module-level JSX initializer written
without wrapping parentheses, because JSX tags are not brackets:
`const sample = <pre>` followed by import-shaped text leaves the depth at
zero. What does separate it is that those lines start no statement. The
character before a real import, once trivia is skipped, is the start of the
file, the end of a previous statement, or the closing quote of a module
specifier, which is how the previous import ends in a file that omits
semicolons. JSX text is preceded by `>`, which ends nothing.

Measured against the tree before adopting it: of the 9801 imports the
scanner accepts today, that rule keeps 9801 and rejects none.

A regex after an unbraced control head, `if (ok) /`/.test(text);`, was read
as a division because of the closing paren. A control statement's
parentheses produce no value, so the scan now walks back to the matching
`(` and reads the word in front of it.

Five more self-test cases, 34 in total, including a division after a call,
a file that omits semicolons, and an import after a function declaration,
so the new rule cannot be satisfied by quietly ignoring more. Live tree
clean across 2238 files.

* Read only the import prologue, and stop hand-lexing TypeScript

Seven times now a whole-file scan has been reported for calling valid
TypeScript a duplicate: source quoted inside a test fixture, a backtick
inside a regex pairing with a later template, a code sample rendered as JSX
text, a module-level JSX initializer with no wrapping parentheses, a nested
template, and JSX text after an expression container. Each fix was correct
and the next hole was already there. The shape of the problem is that
reading TypeScript as raw text needs a lexer, and half a lexer keeps finding
new ways to be wrong in the direction that stops other people's work, since
this gate runs unconditionally on Source lint.

So the scan is bounded instead. It reads the import prologue, meaning the
run of imports, comments and directives at the top of the file, and stops at
the first statement that is not one. A prologue cannot contain a template, a
regex or JSX, so nothing that merely looks like an import can appear in it,
and all seven become impossible rather than handled. The masking, the regex
recogniser, the bracket-depth rule and the statement-boundary rule all go
with it: 362 lines removed, 125 added.

The cost is stated rather than hidden. An import written after other
top-level code is not read, so a duplicate involving one is missed: 611 of
9801 import declarations here, across 19 files. That is a false negative,
which leaves the build where it was before this check existed and which tsc
still catches. A false positive fails CI on correct code. Given the choice,
this misses those.

19 self-test cases. The six false positives above are kept as cases, so a
later change that widens the scan fails here rather than in CI, and so is
the stated cost, so it stays a decision rather than a surprise. The unslothai#8470
regression is still caught verbatim, the live tree is clean across 2238
files, and a real duplicate planted in a file full of fixtures is still
reported on the right line.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant