* feat(web): add graph-load skip decision helper and node threshold (#2178)
* feat(web): skip graph download in connectToServer for chat-only mode (#2178)
* feat(web): add graphMode state and empty-graph chat-only handling (#2178)
* feat(web): read and thread ?skipGraph URL param through connect flow (#2178)
* feat(web): chat-only empty state with load-graph-anyway escape hatch (#2178)
* style(web): apply prettier formatting to graph-load files (#2178)
* fix(review): apply autofix feedback
- Fail-safe confirm + authoritative node count (P1: prevent re-triggering the hang via Load-graph-anyway when count unknown)
- In-flight guard on loadGraphAnyway (P1: double-fire)
- Honor explicit ?skipGraph in onAnalyzeComplete and DropZone (R6/U4)
- Extract buildGraphFromConnectResult shared helper (DRY across 3 connect sites)
- Add tests: switchRepo skip path, threshold config override, loadGraphAnyway error path, confirm fail-safe, in-flight guard
* fix(review): address tri-review findings
- P1 (correctness+adversarial+risk): stop the cross-repo / F5 chat-only leak.
loadGraphAnyway no longer persists ?skipGraph=0, and onAnalyzeComplete +
DropZone no longer inherit a stale ?skipGraph for a different repo — both
could bypass auto-detect and re-trigger the #2178 hang. ?skipGraph is now a
bookmark hint honored only by the initial auto-connect; in-session repo
changes auto-detect.
- P2 (performance): auto-detect now also skips on edge count (edge-driven
force-layout cliff), not just nodes; LARGE_GRAPH_EDGE_THRESHOLD default 50K.
- P2 (julik): reset graphMode/chatOnlyNodeCount at the top of switchRepo so a
failed switch can't leave a stale chat-only overlay.
- P2 (julik): set serverBaseUrl before awaiting handleServerConnect in
auto-connect so the Load-graph-anyway button isn't briefly a no-op.
- P2 (risk): hide the misleading '0 nodes / 0 edges' stats in chat-only mode
(Header + StatusBar).
- P2 (performance): guard the GraphCanvas layout effect against the empty
chat-only graph.
- Tests: edge-threshold decision + connectToServer edge-trigger; load-anyway
no longer asserts URL persistence.
* fix(web): make Load-graph-anyway cancellable, unmount-safe, fail-safe confirm (#2178)
- AbortController + mountedRef: cancel the in-flight download on unmount and
guard every post-await setState by the mounted ref (an abort surfaces as a
BackendError, not a DOMException AbortError, so name-checks would miss it)
- Stale-result guard: a load-anyway that resolves after a concurrent switchRepo
no longer clobbers the new repo's graph/mode/count
- GraphCanvas confirm fails SAFE (treat as declined) when window.confirm is
unavailable or throws, instead of silently proceeding into a large download
* fix(web): make the AI agent and chat surface aware of chat-only mode (#2178)
- buildDynamicSystemPrompt + createGraphRAGAgent take a chatOnly flag and append
a note (both prompt branches) that supersedes VISUAL GROUNDING: the graph isn't
loaded, [[Type:Name]] node citations won't highlight, prefer [[path:START-END]]
- initializeAgent resolves chatOnly = opts ?? graphModeRef.current==='chatOnly':
connect-flow callers (handleServerConnect, switchRepo, loadGraphAnyway re-init)
pass it explicitly; lazy/settings re-inits fall back to live mode via the ref
- loadGraphAnyway re-inits the agent (chatOnly:false) after a full load so the
prompt drops the note
- RightPanel shows a chat-only banner so the degradation is visible where AI
output renders (en + zh-CN)
* fix(web): streaming circuit breaker for graphs with missing size stats (#2178)
- GraphTooLargeError + a mid-stream breaker in parseNdjsonGraphResponse: count
nodes/relationships as they arrive and abort (cancel reader in try/finally,
then throw) the moment either crosses its limit — reusing the existing node/
edge thresholds, no new magic constant. Throwing right after the offending
push means a later error record in the same chunk can't pre-empt it.
- fetchGraph gains optional maxNodes/maxEdges (off by default → existing callers
unchanged). connectToServer arms them only for auto-detect downloads
(skipGraph !== false) and catches GraphTooLargeError → chat-only, re-throwing
every other error. This backstops the no-stats fail-open path that could
otherwise re-trigger the original hang.
* chore(autofix): apply prettier + eslint fixes via /autofix command
---------
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
* Initial plan
* Allow RFC1918 LAN origins in requireLocalhostOrigin
* Harden LAN origin parsing in middleware tests
* Refactor private IPv4 checks into shared server helper
* fix: scope origin guard to server's bound host, fix [::1], guard all write routes
- P1: Replace blanket RFC1918 trust with same-host check — only the server's
own bound host is allowed (via `createLocalhostOriginGuard(host)`), not
every device on the LAN.
- P2: Fix dead `::1` branch — compare against `'[::1]'` (with brackets) as
returned by WHATWG URL parser.
- P3: Update 403 message to "same-host origins" and doc comments.
- Out-of-scope: Add `requireLocalhostOrigin` to `DELETE /api/repo`,
`POST /api/embed`, `DELETE /api/embed/:jobId`, `DELETE /api/analyze/:jobId`.
- Tests: Add [::1] regression, ftp://, null origin, direct private-ip.ts
unit tests, and createLocalhostOriginGuard bound-host tests.
* fix: cast route params to string when middleware breaks type inference
* chore(autofix): apply prettier + eslint fixes via /autofix command
* fix(test): update rate-limit test regex to match multi-line embed route registration
* fix(ip): normalize boundHost and keep wildcard binds loopback-only
The same-host write guard compared the raw `--host` string to the WHATWG
`URL.hostname` of the Origin, so it silently 403'd legitimate same-host
browser writes for several bind forms:
- mixed-case hostnames (`MyHost.local` vs lowercased `myhost.local`)
- non-loopback IPv6 (`fe80::1` vs bracketed `[fe80::1]`, and non-canonical
forms like `fe80:0:0:0:0:0:0:1` / `::ffff:127.0.0.1`)
- wildcard binds (`0.0.0.0` / `::`), the CLI-advertised remote-access config
Canonicalize boundHost once at guard construction through `new URL().hostname`
(provably the same form the Origin is parsed into), and treat wildcard binds as
having no single host identity → writes stay loopback-only. We deliberately do
NOT fall through to RFC1918 for wildcards (that would re-open whole-LAN reach).
`createServer` now warns when bound to a wildcard so a remote-access deployment
is not silently write-blocked.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(ip): tag origin-block 403 with a machine-readable code and surface it in the web client
The write-route Origin guard returned a 403 with only a human-readable
`error` string, so clients could not distinguish an origin block from any
other 403. The hosted web client (gitnexus.vercel.app driving a local
backend) swallowed the resulting failure: the repo delete button caught the
error and only `console.error`'d it, so it silently no-op'd.
- Server: add a stable `code: 'origin_not_allowed'` discriminator to the 403 body.
- Web client: `assertOk` reads `body.code` and maps `origin_not_allowed` to a new
`BackendError` code `origin_blocked`; `formatBackendError` renders an actionable
i18n message (en + zh-CN) instead of the generic client message.
- Header: surface the delete failure inline instead of swallowing it to console.
Scope note: the embedding-status badge (EmbeddingStatus.tsx) hides in backend
mode (its `serverBaseUrl` guard), so it is not the surface where an origin-block
embed error appears; a dedicated backend-mode embedding-error surface is deferred
with the broader hosted-UI mode-awareness follow-up.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(ip): remove unused isValidIpv4Address export
`isValidIpv4Address` had no `src/` consumer — only its own test imported it.
It was a leftover from the reverted RFC1918-middleware approach (the same-host
guard now compares against a canonicalized bound host, not an IPv4 validity
check). Remove the export and its orphaned test block. `parseIpv4Octets` stays
(it feeds `isRfc1918PrivateIpv4`, which CORS `isAllowedOrigin` still uses).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(web): replace broken Browse-for-folder with server-side directory picker
The "Browse for folder" button used `<input type="file" webkitdirectory>`
which only exposes relative paths via `webkitRelativePath`. The code
extracted just the folder name (e.g. `myproject`), causing the server to
reject it with "path must be an absolute path". No browser API can
expose absolute filesystem paths, so the approach was fundamentally
broken on all platforms.
- Add `GET /api/fs/list` endpoint that lists subdirectories at a given
absolute server-side path (rate-limited, validated)
- Add `listDirectories()` client function in backend-client.ts
- Add `DirectoryPicker` modal component with breadcrumb navigation
- Replace broken `webkitdirectory` input in RepoAnalyzer with the new
server-side directory picker
- Update i18n strings (en + zh-CN)
- Add unit tests for the new endpoint (9 tests)
Docker users can now browse `/workspace/` and other container paths
directly from the UI. Manual path entry continues to work unchanged.
Closes#1518
* test(e2e): add Playwright tests for server-side directory picker
13 Playwright e2e tests covering the full DirectoryPicker flow:
- Open/display: modal opens, shows root dirs, displays current path
- Navigation: click into dirs, breadcrumb back-nav, home button
- Selection: populates path input, returns absolute path, close without selecting
- Edge cases: empty dir, API error, manual typing still works
Also updates existing onboarding.spec.ts to match the renamed
"Browse server directories" button, and adds data-testid attributes
to DirectoryPicker and RepoAnalyzer for reliable e2e targeting.
* fix(a11y): add accessibility and UX polish to DirectoryPicker
- Add role="dialog", aria-modal, aria-label to the modal panel
- Add aria-label to close button, home button
- Add aria-hidden to decorative icons (chevrons, backdrop)
- Add role="status" to loading spinner with sr-only label
- Add role="alert" to error state
- Add aria-current="location" to active breadcrumb segment
- Wrap breadcrumb in nav landmark with aria-label
- Add Escape key handler to dismiss the modal
- Auto-focus the modal panel on open
- Add focus-visible ring styles to all interactive elements
(matches existing focus-visible:ring-2 ring-accent/40 pattern)
- Increase breadcrumb button padding (px-1.5 py-1) for better
touch targets
- Increase directory entry padding (py-2.5) for touch comfort
- Add active:bg-hover/70 pressed state on directory entries
- Add active:bg-accent/80 pressed state on select button
* chore(autofix): apply prettier + eslint fixes via /autofix command
* fix: skip traversal guard for bare root paths in /api/fs/list (#2109)
* fix(web): replace server-side directory picker with secure folder upload
PR #1850 review found the new GET /api/fs/list directory-browsing endpoint
enumerated any absolute server path (CodeQL js/path-injection, plus a DoS and
cross-origin enumeration via the CORS/PNA allow-list). Browsers can't hand the
server an absolute path, so rather than harden the endpoint, remove it and
upload the folder instead — webkitdirectory exposes the file contents.
- Add POST /api/analyze/upload: busboy-streamed multipart ingest into an
mkdtemp sandbox under UPLOAD_ROOT with resolve-then-contain write
sanitization, hard size/count/dir caps, manifest-first ordering, and
guaranteed cleanup; promote (atomic same-filesystem rename, no EXDEV) and
analyze via the shared job/worker machinery, never returning a server path.
- Frontend: <input webkitdirectory> upload flow with client-side filtering
(.git/node_modules/build), XHR progress, accessibility, en/zh-CN i18n.
- Remove /api/fs/list + handleFsListRequest, DirectoryPicker, listDirectories
and their tests.
- Harden the adjacent /api/analyze {path} route: localhost-only CORS on write
routes + realpath/exists/isDir validation replacing the inert
normalize!==resolve guard.
- Extend DELETE /api/repo cleanup to upload dirs (by entry.path) and add a
startup sweep for orphaned staging dirs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(review): resolve CodeQL path-injection + CSRF introduced by the upload change
The first push surfaced two new CodeQL alerts in the newly-added code (the
upload sandbox itself passed — its resolve-then-contain sanitizer is recognized):
- HIGH js/path-injection at the analyze route: the KTD11 in-route
`fs.realpath(repoLocalPath)` / `fs.stat` was a user-controlled filesystem
read with no security gain (the worker already reads the path; cross-origin
reach is closed by requireLocalhostOrigin). Drop the in-route fs calls; keep
only the absolute-path check + the localhost-origin guard.
- MEDIUM js/client-side-request-forgery: the new raw `xhr.open` was a fresh
request sink. Route the upload through the shared, origin-validated
fetchWithTimeout instead (the centralized sink all other calls use). Trades
the upload-progress percentage for an indeterminate "Uploading…" state.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(review): resolve tri-review findings on the upload flow
A multi-agent review of the upload implementation surfaced a P0 plus several
P2/P3s; all are addressed here.
- P0: the upload handler took the single analysis slot (createJob) before
validating/promoting, so any failure in that window left a queued job that
was never failed — wedging ALL analysis until restart (trivially triggered by
a single-segment manifest). Now: validate the folder before taking the slot,
release it via failJob on any pre-launch error, and reject single-segment /
multi-top manifests during ingest (also fixes a silent file-drop).
- CI: rate-limit.test's source-regex broke when Prettier wrapped the
/api/analyze registration; made it wrapping-tolerant.
- Resource: the startup sweep now also removes stale promoted upload dirs with
no .gitnexus index (orphans from analyses that failed before registering).
- Frontend: guard against post-unmount SSE opening, reset upload state on
cancel/mode-change, guard concurrent uploads, fall back to the folder name,
add aria-busy, and fix the {{count}} plural ("1 files").
- Maintainability: extract launchAnalysisWorker into analyze-launch.ts (DI +
typed WorkerMessage IPC), move requireLocalhostOrigin to middleware.ts, share
REPO_NAME_PATTERN, tighten UploadJobRef, name the collision-retry constant.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(web): reset isMountedRef on mount (StrictMode double-invoke)
The mount effect set isMountedRef=false on cleanup but never back to true on
re-mount, so under React StrictMode's mount->unmount->mount the ref stayed
false for the component's lifetime — trackJob then always early-returned and
the upload never advanced past 'starting' (caught by the folder-upload e2e).
Set it true at the start of the effect.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(review): de-flake upload-ingest cleanup test via injectable staging root
ingestUpload gains an IngestOptions.root override (mirroring SweepOptions.root)
so the test asserts cleanup against a per-test mkdtemp root instead of counting
global ~/.gitnexus/uploads/.staging-* entries, which raced parallel forks.
Production default stays UPLOAD_ROOT (promote rename same-filesystem invariant).
* fix(web): make stale analyze/upload requests inert after mode switch, cancel, or unmount
A folder upload (or URL analyze) still in flight when the user switched modes
could resolve later, call trackJob(), and drive the old job's SSE stream under
the new mode's form. The only guard was isMountedRef — mode change and cancel
never unmount the component.
- requestControllerRef: per-request AbortController doubling as the staleness
token (captured per closure, checked after the await; the abort error is
matched via signal.aborted, never error identity, since it surfaces both as
BackendError('Request aborted') and as a raw AbortError from response.json())
- uploadFolder() now takes an optional AbortSignal; fetchWithTimeout already
merges caller signals via AbortSignal.any
- a stale-but-created job gets a fire-and-forget cancelAnalyze(jobId) (skipped
when a live tracking session owns the id) so the single analyze slot is freed
- handleModeChange early-returns on same-tab clicks and resets phase to input
so an aborted request can't strand the form at 'starting'
- fixed the stale breaker comment: resilientFetch records AbortError as
breaker-neutral (recordNeutral), not as a retryable-network penalty
* refactor(web): consolidate stale-request guard plumbing
- single invalidateRequest() helper for the abort+null pattern (4 sites)
- drop isMountedRef checks subsumed by the aborted-controller token
(unmount aborts the controller, and unlike isMountedRef the token stays
correct across a StrictMode unmount/remount)
- dedup the component test's render/mock scaffolding
- countStaging filters on the exported STAGING_PREFIX, not a magic string
* fix(web): scope stale-job cancellation to the upload path
Code review caught a regression in the first cut: URL analyzes dedup-alias by
repo (createJob returns the existing active job's id), so a stale resolution's
fire-and-forget cancel could kill a job another session — or the user's own
fresh resubmit — is actively watching; the jobIdRef ownership guard was
order-dependent and instance-local. Uploads always own a fresh, never-deduped
job, so the cancel is kept (unconditionally) there and dropped on the URL path,
where a same-URL resubmit re-attaches via dedup and the server's job timeout /
TTL sweep bounds the slot occupancy.
Also: remove the isMountedRef machinery outright (zero readers remain — the
aborted-controller token subsumes it and stays correct across StrictMode
remounts), make the e2e abort check ERR_ABORTED-specific, and let a broken
test root fail loudly instead of passing vacuously.
---------
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Sparsh <73558748+prajapatisparsh@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(web): align agent system prompt with registered tools
Rewrites BASE_SYSTEM_PROMPT to fix tool-name mismatches, citation format,
and schema guidance from PR #14 tri-review, and adds unit tests that
guard prompt ↔ tool registry parity.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(web): enforce agent prompt/tools parity and harden assertions
U1: assert GRAPH_RAG_TOOL_NAMES equals the names createGraphRAGTools actually registers (via a no-op stub backend), closing the const<->registration drift gap the prompt-parity test previously missed.
U2: make the forbidden-name guard word-boundary (catches bare-prose mentions, not just backticked); make the highlight_in_graph guarantee registry-level (reword-proof) plus a presence check; add a parser-recognized [[Type:Name]] symbol-citation assertion.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(web): drop test-only GRAPH_RAG_TOOL_NAMES from llm barrel
U3: GRAPH_RAG_TOOL_NAMES has no runtime consumer -- the parity test imports it directly from ./tools -- so remove it from the public index.ts barrel re-export. Update the constant's doc comment to name the registration<->const<->prompt coupling now enforced by agent-prompt.test.ts.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(test): derive symbol-ref assertion from NODE_REF_REGEX
Source the symbol-citation assertion from the UI parser's own NODE_REF_REGEX instead of a hardcoded 4-label subset, so the test tracks the parser's allowlist rather than forking it. Also drop a redundant array spread and an unnecessary readonly-tuple cast surfaced by the simplify pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(web): forbid affirmative highlight_in_graph call instructions
Code review noted the registry-absence + bare-presence pair would pass if a future prompt edit affirmatively instructed calling highlight_in_graph (string present, still not registered). Add an assertion that the prompt never says use/call/invoke highlight_in_graph -- restoring the protective intent of the replaced negation check without its brittleness.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(web): stop Nexus AI agent when user clicks Stop
Wire AbortController through chat streaming so Stop cancels the LangGraph
run instead of only hiding the loading UI. Fixes#1615.
* fix(web): address PR review feedback for Nexus AI stop
Guard stream cleanup against Stop-then-Send races, remove dead cancelled
handler, tighten abort error detection, add stopped tool-call status, and
extend abort unit tests. Fixes#1615.
* chore(autofix): apply prettier + eslint fixes via /autofix command
* fix(web): address review findings for Nexus AI stop/cancel
- Fix race conditions in useAppState.tsx abort lifecycle:
- Replace stale isChatLoading closure guard with chatStateRef
- Track and cancel rAF handles in stopChatResponse/finally
- Move cancelled chunk check before onChunk dispatch
- Simplify finally block to unconditional cleanup via chatStateRef
- Guard tool_result from overwriting stopped status
- Have clearChat abort in-flight streams before clearing
- Reorder isAbortError to check error identity before signal.aborted
- Refactor AgentStreamChunk to discriminated union for exhaustive switch
- Fix test assertions to use exact .toEqual() per DoD §2.7
- Add test for plain Error with name AbortError
- Remove dead markStopped alias, simplify signal spread-conditional
---------
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Test <test@example.com>
* feat(graph-view): add tree and circles layout modes
Add alternate graph layouts to the web viewer with new graph view state, canvas controls, adapters, and Sigma layout logic for tree and concentric-circle rendering. Include layout and adapter tests plus tree-view E2E coverage aligned with the English UI labels, and tune node visibility, edge layering, large-graph behavior, and tree-layer spacing so the new views stay readable. Follow up the tree-view work by keeping noisy variables hidden by default and mapping Property/Const icons so filter coverage stays in sync with the expanded node taxonomy.
Co-authored-by: OpenAI Codex <noreply@openai.com>
AI-model: GPT-5 Codex
* fix(web): cap tree layout spring iterations and remove unused variable
Finding A (blocker): calculateTreeLayout runs 14 synchronous spring
iterations over all edges and nodes — O(N×E×14) + O(N log N) per layer
per iteration — with no size guard. At 10K+ nodes this freezes the
main thread for several seconds.
Fix: make SPRING_ITERATIONS adaptive:
- N > 10 000 → 0 iterations (proportional initial layout only)
- N > 3 000 → 4 iterations
- otherwise → 14 iterations (unchanged behaviour for small graphs)
Also removes the unused `const r` at useSigma.ts:1314, which was a
leftover after the radial-resistance decomposition was removed.
This clears the CodeQL "unused variable" warning (Finding G).
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* test(graph-adapter): add circles adapter tests and tree layout perf bound
Finding B (high): knowledgeGraphToCirclesGraphology had zero test
coverage. Adds three new tests:
- ring placement: verifies Folder→ring 0, File→ring 1, Function→ring 3
and confirms circles-specific attributes (circlesRing, circlesAnchorX/Y)
are set while tree attributes (treeAnchorX/Y) are absent.
- edge styling: CONTAINS is marked isHierarchyEdge=true with the
hierarchy colour; CALLS is cross-cutting with its own colour.
- CALLS cross-cutting: a lone CALLS edge between two Functions is
correctly identified as a non-hierarchy edge.
Also adds a performance-bound test for the tree adapter at 2 000 nodes /
4 000 edges (the adaptive 14-iteration path) asserting completion within
2 s — catches regressions to the O(N×E×iterations) main-thread blocking
that Finding A identified.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* refactor(web): rename Tree View → Sequential Layout, Circles → Radial Layout
Aligns the UI labels with standard graph layout terminology from the
Cambridge Intelligence taxonomy (cambridge-intelligence.com/blog/automatic-graph-layouts):
Tree View → Sequential Layout (顺序布局)
Circles → Radial Layout (径向布局)
Force Graph → Force Graph (unchanged)
Internal graphViewMode keys ('tree', 'circles', 'force') are unchanged —
only the displayed strings in en/zh-CN locales and the E2E button selectors
are updated.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* perf(web): add adaptive large-graph guards to sequential layout physics
For graphs with N > 5 000 nodes, each rAF frame of runTreeLayout was
doing O(N log N) sort + O(N × k) repulsion pair comparisons (k ≈ 2 400
for a 20 K-node graph spread across 1 080 px at range 130). At that
scale each frame took hundreds of ms, making the canvas appear completely
frozen even though the physics loop was still running.
Fix mirrors the circles layout adaptive strategy:
N > 5 000 (large):
- Skip repulsion pass (O(N × k) → 0)
- Skip spread-force sort (O(N log N) → 0)
- Velocity cap raised to ±12 / ±6 px so nodes cover ground faster
- Damping 0.58, 1 sim step/frame, 30 s max duration
- Looser early-stop thresholds (max v 0.05, avg v 0.03, active 2 %)
N > 1 500 (medium):
- Velocity cap raised to ±6 / ±3 px
- 24 s max duration
- Repulsion and spread still active
N ≤ 1 500 (small):
- Unchanged behaviour (velocity ±3/±2, 18 s, all forces active)
Layer gravity (O(N)) and edge springs (O(E)) run for all graph sizes —
they provide the structural pull that replaces repulsion at large N.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* fix(web): fix stale closure in sigma event handlers breaking node selection
The sigma 'clickNode', 'clickStage', 'enterNode', and 'leaveNode' handlers
are registered in a one-time useEffect (empty dep array). They captured
options.onNodeClick via closure, so they always called the initial version
of handleNodeClick — the one created before the graph loaded where
`if (!graph) return` exits immediately.
Consequence: clicking a node in the canvas never updated the app-level
selectedNode state. This broke:
- The Focus Depth filter (warning "Select a node to apply depth filter"
persisted even after a canvas click)
- The depth hop filter not applying (selectedNode was always null)
- The code panel not opening on canvas node click
Fix: store the three callback props in refs (onNodeClickRef, onNodeHoverRef,
onStageClickRef) and update them synchronously on every render. The sigma
event handlers now read from the refs, so they always invoke the latest
version of the callbacks without needing to re-register.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* fix(web): address three code-review bugs in graph rendering
Bug 1 (useSigma.ts): forces in the tree physics loop were computed once
before the sub-steps loop and reused for every step, causing 2× displacement
on slow frames (>64ms, simulationSteps>1). Fix: move forceX/forceY Maps and
all force accumulation (layer gravity, edge springs, repulsion, spread) inside
the loop so each sub-step integrates from current node positions.
Bug 2 (graph-adapter.ts): all three adapters used `graph.hasEdge(src,tgt)`
as a dedup guard, which silently drops any second edge between the same node
pair. A CALLS relationship between nodes that also have a CONTAINS edge was
always lost. Fix: switch from `new Graph()` to `new MultiGraph()` (allows
multiple edges per pair) and dedup by `rel.id` instead of by node pair.
Bug 3 (graph-adapter.test.ts): the cross-cutting edge styling test never
executed its CALLS branch because Bug 2 dropped the CALLS edge before the
assertion ran. Fix: assert `sigmaGraph.size === 2` and verify both edges
individually after collecting attrs by relationType.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-5
* fix(web): address three code-review bugs in graph rendering
- Move radial layout force accumulation inside the sub-step loop so
forces are recomputed from updated node positions each iteration
instead of using stale forces computed before the loop began
- Revert knowledgeGraphToGraphology from MultiGraph back to Graph with
node-pair deduplication to prevent ForceAtlas2 from double-applying
spring forces for node pairs that share multiple relation types
- Add Target to the lucide-icons import in FileTreePanel.tsx so the
Const node type icon resolves without a ReferenceError
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-6
* fix(web): address four more PR review comments
Edge visibility (useSigma.ts): HAS_METHOD / HAS_PROPERTY edges were hidden
when any edge-type filter was active because those types are not in the EdgeType
union. Normalize HAS_METHOD → DEFINES and HAS_PROPERTY → CONTAINS before the
visibleTypes.includes() guard so Kotlin/Java hierarchy edges follow the same
filter logic as their semantic equivalents.
Force-mode edge styles (graph-adapter.ts): HAS_METHOD / HAS_PROPERTY fell back
to the default gray color in the force-graph adapter because EDGE_STYLES had no
entries for them. Added explicit entries using the same hues as DEFINES/CONTAINS
so force mode renders Kotlin/Java hierarchy edges consistently with tree/circles.
Accessibility (GraphCanvas.tsx, locales): the layout-mode switcher (Force /
Tree / Circles) had no ARIA semantics. Added role="tablist" on the container
and role="tab" + aria-selected on each button. Added the viewModes.label i18n
key (used as aria-label on the tablist) to en and zh-CN locale files.
Flaky test (graph-adapter.test.ts): replaced the hard 2 s wall-clock assertion
with a structural check (node count + edge count) that is deterministic across
CI hardware. Timing tests are inherently flaky and provide no correctness signal.
Co-authored-by: Claude <noreply@anthropic.com>
AI-model: claude-sonnet-4-5
---------
Co-authored-by: OpenAI Codex <noreply@openai.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
* feat(progress): add per-language progress reporting to scope-resolution phase (#1741)
The scope-resolution phase (which can run 74+ minutes on large Java/Kotlin
repos) previously emitted zero progress updates, causing the CLI progress bar
to freeze at ~49% with a stale "Parsing code" label — making users think
the tool was stuck.
- Add `scopeResolution` to PipelinePhase type and PHASE_LABELS
- Add `onProgress` callback to `runScopeResolution` with per-file updates
during the extract loop and sub-phase boundary markers (building scope
model, resolving references, emitting edges)
- Wire progress through `scopeResolutionPhase` with pre-counted file totals,
per-language labels, and pipeline-wide percent mapping (90-95 internal)
- Bump mro/communities/processes percent ranges to 95-100 to maintain
monotonic progress after scope resolution
- Add `scopeResolution` to mro's deps (latent ordering fix: mro reads
EXTENDS edges that scope resolution writes via preEmitInheritanceEdges)
* fix(progress): clamp overallRatio, fire final extract event, fix mro @deps JSDoc
- Clamp overallRatio to [0,1] so percent never exceeds 95 when
readFileContents drops files (langFileCount < totalScopeFiles)
- Fire onProgress for the last file in the extract loop even when
files.length is not divisible by progressInterval
- Update mro @deps JSDoc to include scopeResolution
* fix(progress): ensure bar redraws at every state transition
- Fire initial 'extracting' event at file 0 so the sub-phase label
appears immediately, not after progressInterval files
- Emit a completion event at percent 95 when scope resolution finishes
so the bar definitively reaches the phase ceiling before mro starts
* feat(progress): improve UX with human-readable elapsed, language counter, cleaner labels
- Format elapsed time as "5m 12s" / "1h 20m" instead of raw "(312s)"
for all pipeline phases (CLI-wide improvement)
- Add language counter "[1/3]" to scope-resolution detail so users
know how many languages remain and which is active
- Rename sub-phases for clarity: "building scope model" → "analyzing
types", "emitting edges" → "linking symbols"
- Remove nested parentheses from detail strings for cleaner display
- Expand scope-resolution percent range from 5 to 8 points (90-98
internal → 54-59% display) for more visible bar motion
- Re-allocate mro (98), communities (98-99), processes (99-100)
* feat(progress): typed sub-phases, i18n locales, and test coverage
- Extract ScopeResolutionSubPhase union type with exhaustive switch
guard so adding a sub-phase without updating phase.ts is a compile
error
- Add scopeResolution key to en and zh-CN locale files so the web UI
shows translated labels instead of raw message fallback
- Extract formatElapsed to its own module with 7 boundary-value tests
(0s, 59s, 60s, 3599s, 3600s, 3661s, 7323s)
- Add runScopeResolution onProgress integration test proving sub-phase
order (extracting → analyzing types → resolving references → linking
symbols) and the 0-file early-return path
---------
Co-authored-by: Test <test@example.com>
* feat(web): support GITNEXUS_BACKEND_URL env var for Docker deployments
* fix(docker): escape inline script injection to prevent XSS and add server-level integration tests
- Add jsonForScriptTag() that escapes <, >, & after JSON.stringify to prevent </script> breakout in inline config script
- Sanitize rawBackendUrl in warning log to prevent log injection via newlines
- Replace 5 duplicated-helper injection tests with 7 server-level HTTP integration tests that spawn the real docker-server.mjs with GITNEXUS_BACKEND_URL set
- Add XSS-specific test: URL containing </script> must produce exactly 1 <script> tag
- Add empty-string backendUrl frontend test
- Improve Docker Compose Linux guidance with explicit <server-ip> example
* fix(docker): harden log sanitization, fix error leak, fix killAndWait race
- Broaden log sanitization regex from [\r\n] to [\x00-\x1f\x7f] to strip
all C0 control characters including ANSI escape sequences
- Replace error.message leak in 500 handler with generic string; log the
real error server-side via console.error
- Fix killAndWait TOCTOU race by registering exit listener before kill
and adding post-kill exitCode guard
* fix(docker): handle readFile race to resolve CodeQL file-system-race alert
Wrap readFile in try/catch so the TOCTOU between stat() and readFile()
is handled gracefully — if the file vanishes between the check and the
read, return 404 instead of crashing.
* @
fix(docker): eliminate TOCTOU race and format web components
Replace the previous try/catch approach with fs.promises.open() to
get a file handle, then use handle.stat()/readFile()/createReadStream()
from the same fd — properly eliminates the CodeQL "file system race
condition" alert by removing the window between stat() and read.
Also runs prettier on the 5 web component files that were failing
the format CI check.
@
* chore(autofix): apply prettier + eslint fixes via /autofix command
* chore: trigger CI
* @
fix(docker): pass GITNEXUS_BACKEND_URL to the web container
The env var was documented but commented out, so docker-server.mjs
never received it and the config injection was dead. Uncomment
the environment block with a passthrough default so users can
set GITNEXUS_BACKEND_URL in .env or their shell for remote/custom
deployments.
@
* @
fix(docker): eliminate stat() to resolve CodeQL js/file-system-race
CodeQL pairs any stat() (FileCheck) with a subsequent open() (FileUse)
on an aliased path. The previous approach kept stat() for directory
detection, which the analyzer flagged regardless of the fd-based reads.
Replace stat() entirely with open() + handle.stat(). On Linux (Docker),
open() succeeds for directories, so handle.stat().isDirectory() detects
them without a standalone stat() call. This removes the FileCheck node
from the data-flow graph, eliminating the alert at its source.
@
* @
fix(docker): break CodeQL path alias chain between open() calls
CodeQL js/file-system-race pairs two open() calls when their path
arguments are data-flow aliased. The previous approach derived
the fallback path from the request path (resolve(initialPath,
index.html)), creating an alias chain the analyzer could trace.
Restructure so the SPA fallback uses a module-level constant
(spaFallback = resolve(root, index.html)) with zero data-flow
from the request. The two open() calls now have provably
independent path arguments, eliminating the FileCheck/FileUse pair.
Also simplifies the logic: for an SPA, all non-file requests serve
root/index.html — no directory/index.html detection needed since
the client-side router handles subroutes.
@
---------
Co-authored-by: Test <test@example.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>