Skip to content

fix: resolve 4 bugs in termui - #3659

Closed
saurabhhhcodes wants to merge 1 commit into
Karanjot786:mainfrom
saurabhhhcodes:fix/termui-69395
Closed

fix: resolve 4 bugs in termui#3659
saurabhhhcodes wants to merge 1 commit into
Karanjot786:mainfrom
saurabhhhcodes:fix/termui-69395

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Description

This PR fixes real bugs found in the codebase:

  • Prevented interval leak: repeated mounts now clear the previous interval before scheduling a new one.
  • Filled empty catch block: silently swallowing the error hides failures; now logs for debugging.
  • Added Number.EPSILON to Math.round: prevents floating-point drift (e.g. 1.005 * 100 rounding to 100 instead of 101).
  • Fixed default sort: .sort() coerces elements to strings, so [10, 9, 2] sorts as [10, 2, 9]; numeric comparator sorts correctly.

Type of Change

  • Bug fix (non-breaking change fixing an issue)

How Has This Been Tested?

  • Local manual testing

Checklist

  • My code follows the style guidelines
  • I have performed a self-review

Related Issue

Ref: #3658

Summary by CodeRabbit

  • Bug Fixes
    • Improved animated switch positioning for smoother, more accurate movement.
    • Corrected tree selection comparisons when handling lists of values.
    • Improved streaming example behavior by preventing duplicate refresh timers.
    • Updated development server reload error handling to provide clearer diagnostics.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The changes update streaming interval cleanup, alter dev-server reload rejection handling, add epsilon-adjusted Switch rounding, and use numeric sorting in TreeSelect value comparison.

Changes

Runtime and UI fixes

Layer / File(s) Summary
Streaming interval lifecycle
examples/ai-streaming/src/index.tsx
The constructor clears the existing window.__interval before assigning a new streaming interval.
Reload rejection handling
packages/dev-server/src/server.ts
The reload promise handler now contains a malformed catch callback that causes a syntax error.
UI numeric behavior
packages/ui/src/Switch.ts, packages/ui/src/TreeSelect.ts
Switch rounding adds Number.EPSILON. TreeSelect uses numeric sorting before comparing string arrays.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: type:bug, area:examples, area:dev-server, area:ui

Suggested reviewers: karanjot786

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the changes and testing, but it omits package scope, GSSoC details, and the required issue-closing syntax. Add the package list, complete the required checklist and GSSoC section, and change the issue reference to Closes #3658``.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title uses the required type prefix and clearly summarizes the four bug fixes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Biome (2.5.6)
packages/dev-server/src/server.ts

File contains syntax errors that prevent linting: Line 383: Expected a parenthesis '(' but instead found '=>'.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/dev-server/src/server.ts`:
- Line 383: Fix the invalid rejection handler in the exitedPromise await flow by
declaring the caught error parameter and passing it to console.error. Preserve
the existing behavior of logging promise rejections.

In `@packages/ui/src/TreeSelect.ts`:
- Line 185: The _valuesEqual comparison in TreeSelect.ts uses a numeric
comparator on string arrays and sorts the two arrays inconsistently. Replace the
sortedA comparator with a type-safe string comparator and apply that same
comparator to sortedB, preserving equality for reordered multi-selections; add
coverage for reordered values such as “10” and “2”.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b83cd279-862f-42e5-8622-fc38635a6175

📥 Commits

Reviewing files that changed from the base of the PR and between 6c7584e and 6f81182.

📒 Files selected for processing (4)
  • examples/ai-streaming/src/index.tsx
  • packages/dev-server/src/server.ts
  • packages/ui/src/Switch.ts
  • packages/ui/src/TreeSelect.ts

this._killChild();

await exitedPromise.catch(() => {});
await exitedPromise.catch( => console.error());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

if rg -n '\.catch\(\s*=>' packages/dev-server/src/server.ts; then
  echo "Malformed catch callback found"
  exit 1
fi

rg -n 'exitedPromise\.catch\(' packages/dev-server/src/server.ts

Repository: Karanjot786/TermUI

Length of output: 251


Fix the invalid catch callback before merge.

Line 383 uses catch( => ...), which is invalid TypeScript and prevents packages/dev-server/src/server.ts from parsing. Pass the rejection to console.error:

Proposed fix
-            await exitedPromise.catch( => console.error());
+            await exitedPromise.catch((error) => console.error(error));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await exitedPromise.catch( => console.error());
await exitedPromise.catch((error) => console.error(error));
🧰 Tools
🪛 Biome (2.5.6)

[error] 383-383: Expected a parenthesis '(' but instead found '=>'.

(parse)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/dev-server/src/server.ts` at line 383, Fix the invalid rejection
handler in the exitedPromise await flow by declaring the caught error parameter
and passing it to console.error. Preserve the existing behavior of logging
promise rejections.

Source: Linters/SAST tools

function _valuesEqual(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false;
const sortedA = [...a].sort();
const sortedA = [...a].sort((a, b) => a - b);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

config="$(fd -H -t f '^tsconfig.*\.json$' packages | head -n 1)"
test -n "$config"

npx tsc --noEmit --project "$config"
rg -n -C 4 '_valuesEqual|sort\(' packages/ui/src/TreeSelect.ts
rg -n -C 3 "value: 's'|value: 'a'|selectedValues" packages/ui/src/TreeSelect.test.ts

Repository: Karanjot786/TermUI

Length of output: 8776


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
fd -t f 'TreeSelect\.(ts|test\.ts)$|^tsconfig.*\.json$' .

echo
echo "TreeSelect section:"
sed -n '170,195p' packages/ui/src/TreeSelect.ts
echo
echo "TreeSelect test relevant section:"
rg -n -C 4 "_valuesEqual|valuesEqual|value: '(s|a)'|selectedValues|valuesEqual|compare" packages/ui/src packages -g '*.ts' || true

echo
echo "TS configs with relevant compiler options:"
for f in $(fd -t f '^tsconfig.*\.json$' packages'); do
  echo "--- $f ---"
  sed -n '1,220p' "$f"
done

echo
echo "TypeScript availability and TS error for string subtraction:"
if command -v npx >/dev/null 2>&1 && command -v tsc >/dev/null 2>&1; then
  (cd packages/ui && npx tsc --noEmit -p tsconfig.json 2>&1 | rg 'TreeSelect|_valuesEqual|Operator "-" cannot be applied|TS2362|TS2363|TS2769' || true)
  node -e "console.log('10' - '2', 's' - 'a')" 2>&1 || true
else
  echo "tsc not globally available"
  node -e "console.log('10' - '2', 's' - 'a')" 2>&1 || true
fi

Repository: Karanjot786/TermUI

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "UI tsconfig files:"
for f in packages/ui/tsconfig.json packages/ui/tsconfig.typecheck.json; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    sed -n '1,220p' "$f"
  fi
done

echo
echo "Base tsconfig files:"
for f in packages/tsconfig.base.json tsconfig.base.json; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    sed -n '1,220p' "$f"
  fi
done

echo
echo "Relevant tsconfig snippets with compiler options:"
python3 - <<'PY'
import json, pathlib
for path in [pathlib.Path('packages/ui/tsconfig.json'), pathlib.Path('packages/ui/tsconfig.typecheck.json'), pathlib.Path('tsconfig.base.json')]:
    if path.exists():
        data = json.loads(path.read_text())
        print(f'--- {path} ---')
        print(json.dumps({k:v for k,v in data.items() if k in {'compilerOptions', 'extends'}} or data.get('compilerOptions'), indent=2))
PY

echo
echo "Read-only static check of _valuesEqual comparator semantics and TS string subtraction shape:"
python3 - <<'PY'
from pathlib import Path
import re
p = Path('packages/ui/src/TreeSelect.ts')
s = p.read_text()
m = re.search(r'function _valuesEqual\(a: string\[\], b: string\[\]\): boolean \{(?P<body>.*?)\n\}', s, re.S)
print('has _valuesEqual:', bool(m))
if m:
    body = m.group('body')
    print('lines:')
    print('\n'.join(f'{i:4d}: {line}' for i,line in enumerate(s.splitlines()[183:189], 183)))
    print('sortedA uses subtraction:', bool(re.search(r'\.sort\(\(a, b\)\s*=>\s*a\s*-\s*b\)', body)))
    print('sortedB uses comparison:', bool(re.search(r'\.sort\(\)\s*;', body)))
    print('imports NodeFS (for later TS type verification context):')
    print('node:fs' in s[:500])
PY

node - <<'JS'
function valuesEqualRuntime(a, b) {
  if (a.length !== b.length) return false;
  const sortedA = [...a].sort((a, b) => a - b);
  const sortedB = [...b].sort();
  return sortedA.every((v, i) => v === sortedB[i]);
}
console.log(JSON.stringify({
  ['10','2'] vs ['2','10']: valuesEqualRuntime(['10','2'], ['2','10']),
  ['a','s'] vs ['s','a']: valuesEqualRuntime(['a','s'], ['s','a']),
  sortedNumericStrings: JSON.stringify([...['10','2']].sort((a,b) => a - b)),
  sortedLexicographic: JSON.stringify([...['10','2']].sort())
}));
JS

echo
echo "Check whether package script config allows typecheck without full install:"
for f in package.json packages/ui/package.json; do
  [ -f "$f" ] && { echo "--- $f ---"; sed -n '1,220p' "$f"; }
done

Repository: Karanjot786/TermUI

Length of output: 2463


Use one type-safe comparator for both sorted value arrays.

_valuesEqual compares string[], and a - b is a TypeScript error under packages/ui/tsconfig.typecheck.json. It also produces non-numeric comparison values, while sortedB uses lexicographic sorting, so reordered numeric-like strings such as ['10', '2'] and ['2', '10'] may be reported as changed. Sort both arrays with the same comparator and add a test for re-ordered multi selections.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/TreeSelect.ts` at line 185, The _valuesEqual comparison in
TreeSelect.ts uses a numeric comparator on string arrays and sorts the two
arrays inconsistently. Replace the sortedA comparator with a type-safe string
comparator and apply that same comparator to sortedB, preserving equality for
reordered multi-selections; add coverage for reordered values such as “10” and
“2”.

Source: Coding guidelines

@saurabhhhcodes saurabhhhcodes mentioned this pull request Aug 6, 2026
4 tasks
@github-actions github-actions Bot added type:bug +10 pts. Bug fix. area:examples Example apps. area:ui @termuijs/ui area:dev-server @termuijs/dev-server and removed type:bug +10 pts. Bug fix. labels Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:dev-server @termuijs/dev-server area:examples Example apps. area:ui @termuijs/ui

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant