Skip to content

refactor(web-ui): split session trash methods out of app#66

Closed
awsl233777 wants to merge 2 commits intomainfrom
chore/web-ui-token-friendly-structure
Closed

refactor(web-ui): split session trash methods out of app#66
awsl233777 wants to merge 2 commits intomainfrom
chore/web-ui-token-friendly-structure

Conversation

@awsl233777
Copy link
Copy Markdown
Collaborator

@awsl233777 awsl233777 commented Apr 3, 2026

Summary

  • extract session trash/settings-tab methods from web-ui/app.js into web-ui/modules/session-trash.methods.mjs
  • keep the existing UI behavior unchanged while shrinking app.js and reducing the amount of context future edits need to load
  • update unit tests to validate the new modular structure and keep session-trash behavior covered after the extraction

Why

The goal of this change is not cosmetic cleanup. It is to make future AI-assisted edits cheaper and safer by:

  • reducing the size of one of the longest web-ui files
  • isolating a cohesive feature slice so later changes can target a smaller module
  • preserving behavior and regression coverage instead of doing a large rewrite

Validation

  • npm test

Summary by CodeRabbit

  • Documentation

    • Enhanced security guidance: default bind address now localhost-only (127.0.0.1) with explicit instructions for enabling LAN access on trusted networks only.
  • Bug Fixes

    • Fixed incorrect skills target state reset behavior in the skills manager.
    • Improved method return value consistency when operations are already in progress.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 3, 2026

@coderabbitai re-review
Stop making breaking changes, do a proper review!

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 3, 2026

@github-actions[bot] Understood. I will redo the review now, strictly limiting feedback to correctness, safety, and quality issues within the existing design — no refactoring, no API/interface/behavior changes, and no breaking changes of any kind.

Please re-iterate: All suggestions must stay within the existing design. No breaking changes.


🧠 Learnings used
Learnt from: github-actions[bot]
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-30T04:47:15.339Z
Learning: In PR `#55` for SakuraByteCore/codexmate, github-actions[bot] repeatedly flagged that CodeRabbit was introducing breaking changes. The maintainer's absolute constraint is: no breaking changes in any review suggestion; limit all feedback to correctness, safety, and quality only within the existing design, without refactoring or altering APIs, interfaces, or behavior.

Learnt from: github-actions[bot]
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-31T12:37:50.988Z
Learning: In PR `#59` for SakuraByteCore/codexmate, github-actions[bot] repeatedly flagged that CodeRabbit was introducing breaking changes. The maintainer's absolute constraint is: no breaking changes in any review suggestion; limit all feedback to correctness, safety, and quality only within the existing design, without refactoring or altering APIs, interfaces, or behavior.

Learnt from: SurviveM
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-29T02:42:32.761Z
Learning: The repository maintainer SurviveM (GitHub: SurviveM, repo: SakuraByteCore/codexmate) prefers that CodeRabbit review suggestions do not introduce breaking changes. Reviews should focus on correctness, safety, and quality without recommending refactors or changes that would break existing APIs, interfaces, or behavior.
✅ Actions performed

Full review triggered.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 3, 2026

📝 Walkthrough

Walkthrough

This PR refactors session-trash UI logic from web-ui/app.js into a dedicated module, updates host binding documentation to default to 127.0.0.1 for security, and adjusts related unit tests to validate the extracted module and CLI parsing patterns.

Changes

Cohort / File(s) Summary
Documentation Updates
README.en.md, site/guide/getting-started.md
Changed default web listen address from 0.0.0.0:3737 (LAN-accessible) to 127.0.0.1:3737 (localhost-only), with added security warnings about unauthenticated admin UI exposure when using 0.0.0.0 on untrusted networks.
Session Trash Refactoring
web-ui/app.js, web-ui/modules/session-trash.methods.mjs
Extracted 354 lines of inline session-trash methods from app.js into a new factory module that exports constants (DEFAULT_SESSION_TRASH_LIST_LIMIT, DEFAULT_SESSION_TRASH_PAGE_SIZE), resolver functions, and createSessionTrashMethods() providing item building, list/count loading, restore/purge/clear actions, state management, and request token handling (380 lines added).
Session Trash Test Updates
tests/unit/config-tabs-ui.test.mjs, tests/unit/session-trash-state.test.mjs
Updated test assertions to validate extracted session-trash methods against the new module instead of inline app code; switched from dynamic function extraction to direct module import; adjusted normalization logic and Claude session index path-related test cases.
Minor Control Flow Updates
web-ui/modules/skills.methods.mjs
Refined openSkillsManager to conditionally reset skills target state only when target changes, and updated scanImportableSkills to return boolean false (instead of undefined) when scan operation is already in progress.
CLI Parsing & Host Resolution Tests
tests/unit/web-run-host.test.mjs
Relaxed CLI pattern matching for DEFAULT_WEB_HOST to accept arbitrary whitespace and quote styles; extended resolveSkillTarget test coverage to reject both target and targetApp input variants.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • SurviveM
  • ymkiux

Poem

🐰 A rabbit hops through tangled code,
With session trash no longer stowed,
In methods.mjs, clean and tidy,
The logic flows (no longer grimy),
Security warns of 0.0.0.0
127.0.0.1 saves the day! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: extracting session trash methods from app.js into a separate module, which is the primary refactoring objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/web-ui-token-friendly-structure
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch chore/web-ui-token-friendly-structure

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.

🔧 ast-grep (0.42.0)
web-ui/app.js

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/unit/session-trash-state.test.mjs`:
- Around line 18-29: The current unit helpers import session-trash.methods.mjs
directly which tests the extracted functions (createSessionTrashMethods,
resolveSessionTrashListLimit, resolveSessionTrashPageSize,
DEFAULT_SESSION_TRASH_LIST_LIMIT, DEFAULT_SESSION_TRASH_PAGE_SIZE) but no longer
verifies that web-ui/app.js actually binds those methods to the UI; add back a
single app-level smoke test that imports the real web-ui/app.js (or requires the
app bootstrap) and asserts that the UI instance exposes the expected
session-trash methods (e.g. createSessionTrashMethods-bound helpers or named
methods) so the extraction wiring is validated end-to-end.

In `@web-ui/modules/session-trash.methods.mjs`:
- Around line 303-309: The normalizeSessionTrashTotalCount helper can return a
floored server value smaller than the currently loaded fallback list; update
normalizeSessionTrashTotalCount(totalCount, fallbackItems) so that after
computing numericTotal and flooring it you return at least fallbackCount (i.e.
Math.max(flooredNumericTotal, fallbackCount)) — keep the existing invalid-number
fallback behavior but ensure the final return value is never less than the
length of fallbackItems to avoid under-reporting sessionTrashCount.

In `@web-ui/modules/skills.methods.mjs`:
- Around line 38-42: The conditional guard around resetSkillsTargetState()
causes state to be retained when reopening the same target; change
openSkillsManager to always call this.resetSkillsTargetState() after setting
this.skillsTargetApp (i.e., remove the targetChanged conditional and keep
assigning this.skillsTargetApp = targetApp then unconditionally invoke
this.resetSkillsTargetState()), referencing the symbols targetApp,
this.skillsTargetApp, targetChanged, and resetSkillsTargetState to locate and
update the code.
🪄 Autofix (Beta)

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 74639b43-b20e-448c-af29-5efda857549e

📥 Commits

Reviewing files that changed from the base of the PR and between 02514bd and 49c6da1.

📒 Files selected for processing (8)
  • README.en.md
  • site/guide/getting-started.md
  • tests/unit/config-tabs-ui.test.mjs
  • tests/unit/session-trash-state.test.mjs
  • tests/unit/web-run-host.test.mjs
  • web-ui/app.js
  • web-ui/modules/session-trash.methods.mjs
  • web-ui/modules/skills.methods.mjs
📜 Review details
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: github-actions[bot]
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-30T04:47:15.339Z
Learning: In PR `#55` for SakuraByteCore/codexmate, github-actions[bot] repeatedly flagged that CodeRabbit was introducing breaking changes. The maintainer's absolute constraint is: no breaking changes in any review suggestion; limit all feedback to correctness, safety, and quality only within the existing design, without refactoring or altering APIs, interfaces, or behavior.
Learnt from: github-actions[bot]
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-31T12:37:50.988Z
Learning: In PR `#59` for SakuraByteCore/codexmate, github-actions[bot] repeatedly flagged that CodeRabbit was introducing breaking changes. The maintainer's absolute constraint is: no breaking changes in any review suggestion; limit all feedback to correctness, safety, and quality only within the existing design, without refactoring or altering APIs, interfaces, or behavior.
Learnt from: SurviveM
Repo: SakuraByteCore/codexmate PR: 0
File: :0-0
Timestamp: 2026-03-29T02:42:32.761Z
Learning: The repository maintainer SurviveM (GitHub: SurviveM, repo: SakuraByteCore/codexmate) prefers that CodeRabbit review suggestions do not introduce breaking changes. Reviews should focus on correctness, safety, and quality without recommending refactors or changes that would break existing APIs, interfaces, or behavior.
🔇 Additional comments (7)
tests/unit/web-run-host.test.mjs (2)

112-112: Regex update improves test resilience without changing intent.

This match pattern is appropriately tolerant to harmless formatting variance in cli.js while still targeting DEFAULT_WEB_HOST precisely.

Based on learnings: no breaking changes in suggestions; focus on correctness/safety/quality within existing design.


201-201: Good coverage addition for explicit target rejection path.

This assertion correctly protects the explicit-invalid-target branch and aligns with current resolveSkillTarget semantics.

README.en.md (2)

127-129: Security messaging and default host wording are clear and accurate.

The localhost-default statement plus explicit LAN exposure warning is precise and user-protective.


237-237: Environment variable default now correctly reflects runtime behavior.

This table entry is consistent with the current default host value and reduces operator confusion.

site/guide/getting-started.md (1)

30-32: 中文启动说明更新到位,且安全提示完整。

默认监听地址与局域网显式开启方式说明一致、清晰,能有效降低误暴露风险。

web-ui/modules/skills.methods.mjs (1)

162-162: Good change: explicit busy-state return value.

Returning false on the busy early-exit path makes the method contract more consistent and avoids ambiguous undefined handling.

tests/unit/session-trash-state.test.mjs (1)

1979-1986: Good contract coverage for the new module exports.

Checking the exported defaults and resolver helpers directly is a useful guardrail for the extracted module surface.

Comment on lines +18 to +29
const sessionTrashModule = await import(pathToFileURL(path.join(__dirname, '..', '..', 'web-ui', 'modules', 'session-trash.methods.mjs')).href);
const {
createSessionTrashMethods,
resolveSessionTrashListLimit,
resolveSessionTrashPageSize,
DEFAULT_SESSION_TRASH_LIST_LIMIT,
DEFAULT_SESSION_TRASH_PAGE_SIZE
} = sessionTrashModule;

function createSessionTrashTestMethods(api, constants = {}) {
return createSessionTrashMethods({ api, constants });
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep one app-level smoke test for the extraction wiring.

These helpers switch the session-trash coverage from parsing web-ui/app.js to importing session-trash.methods.mjs directly. That validates the extracted module in isolation, but this file no longer proves that web-ui/app.js actually binds those methods into the UI instance, which is the risky part of this PR. A broken import/binding in web-ui/app.js could now pass here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/session-trash-state.test.mjs` around lines 18 - 29, The current
unit helpers import session-trash.methods.mjs directly which tests the extracted
functions (createSessionTrashMethods, resolveSessionTrashListLimit,
resolveSessionTrashPageSize, DEFAULT_SESSION_TRASH_LIST_LIMIT,
DEFAULT_SESSION_TRASH_PAGE_SIZE) but no longer verifies that web-ui/app.js
actually binds those methods to the UI; add back a single app-level smoke test
that imports the real web-ui/app.js (or requires the app bootstrap) and asserts
that the UI instance exposes the expected session-trash methods (e.g.
createSessionTrashMethods-bound helpers or named methods) so the extraction
wiring is validated end-to-end.

Comment on lines +303 to +309
normalizeSessionTrashTotalCount(totalCount, fallbackItems = this.sessionTrashItems) {
const fallbackCount = Array.isArray(fallbackItems) ? fallbackItems.length : 0;
const numericTotal = Number(totalCount);
if (!Number.isFinite(numericTotal) || numericTotal < 0) {
return fallbackCount;
}
return Math.floor(numericTotal);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep the normalized trash count at least as large as the loaded fallback list.

This helper now returns the raw floored server value, which means it can shrink below fallbackItems.length. web-ui/app.js Lines 1868-1880 still build the next count from normalizeSessionTrashTotalCount(this.sessionTrashTotalCount, this.sessionTrashItems) + 1, so a stale 0 now becomes 1 even when the UI already has more trash rows loaded. That under-reports sessionTrashCount and can drive the wrong empty/clear-all state.

Minimal fix
         normalizeSessionTrashTotalCount(totalCount, fallbackItems = this.sessionTrashItems) {
             const fallbackCount = Array.isArray(fallbackItems) ? fallbackItems.length : 0;
             const numericTotal = Number(totalCount);
             if (!Number.isFinite(numericTotal) || numericTotal < 0) {
                 return fallbackCount;
             }
-            return Math.floor(numericTotal);
+            return Math.max(fallbackCount, Math.floor(numericTotal));
         },
📝 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
normalizeSessionTrashTotalCount(totalCount, fallbackItems = this.sessionTrashItems) {
const fallbackCount = Array.isArray(fallbackItems) ? fallbackItems.length : 0;
const numericTotal = Number(totalCount);
if (!Number.isFinite(numericTotal) || numericTotal < 0) {
return fallbackCount;
}
return Math.floor(numericTotal);
normalizeSessionTrashTotalCount(totalCount, fallbackItems = this.sessionTrashItems) {
const fallbackCount = Array.isArray(fallbackItems) ? fallbackItems.length : 0;
const numericTotal = Number(totalCount);
if (!Number.isFinite(numericTotal) || numericTotal < 0) {
return fallbackCount;
}
return Math.max(fallbackCount, Math.floor(numericTotal));
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web-ui/modules/session-trash.methods.mjs` around lines 303 - 309, The
normalizeSessionTrashTotalCount helper can return a floored server value smaller
than the currently loaded fallback list; update
normalizeSessionTrashTotalCount(totalCount, fallbackItems) so that after
computing numericTotal and flooring it you return at least fallbackCount (i.e.
Math.max(flooredNumericTotal, fallbackCount)) — keep the existing invalid-number
fallback behavior but ensure the final return value is never less than the
length of fallbackItems to avoid under-reporting sessionTrashCount.

Comment on lines +38 to 42
const targetChanged = targetApp !== this.skillsTargetApp;
if (targetChanged) {
this.skillsTargetApp = targetApp;
this.resetSkillsTargetState();
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Restore unconditional state reset in openSkillsManager to avoid regression.

Line 39-Line 42 makes resetSkillsTargetState() conditional. With repeated opens on the same target (for example, targetApp: 'codex'), previous state is now retained, which changes user-visible behavior and conflicts with the PR goal to keep behavior unchanged.

Suggested fix (behavior-preserving)
 async openSkillsManager(options = {}) {
     const targetApp = this.normalizeSkillsTargetApp(options && options.targetApp ? options.targetApp : this.skillsTargetApp);
-    const targetChanged = targetApp !== this.skillsTargetApp;
-    if (targetChanged) {
+    if (targetApp !== this.skillsTargetApp) {
         this.skillsTargetApp = targetApp;
-        this.resetSkillsTargetState();
     }
+    this.resetSkillsTargetState();
     this.showSkillsModal = true;
     await this.refreshSkillsList({ silent: false });
 },

Based on learnings: "no breaking changes in any review suggestion; limit feedback to correctness, safety, and quality only within the existing design, without refactoring or altering APIs, interfaces, or behavior."

📝 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
const targetChanged = targetApp !== this.skillsTargetApp;
if (targetChanged) {
this.skillsTargetApp = targetApp;
this.resetSkillsTargetState();
}
async openSkillsManager(options = {}) {
const targetApp = this.normalizeSkillsTargetApp(options && options.targetApp ? options.targetApp : this.skillsTargetApp);
if (targetApp !== this.skillsTargetApp) {
this.skillsTargetApp = targetApp;
}
this.resetSkillsTargetState();
this.showSkillsModal = true;
await this.refreshSkillsList({ silent: false });
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web-ui/modules/skills.methods.mjs` around lines 38 - 42, The conditional
guard around resetSkillsTargetState() causes state to be retained when reopening
the same target; change openSkillsManager to always call
this.resetSkillsTargetState() after setting this.skillsTargetApp (i.e., remove
the targetChanged conditional and keep assigning this.skillsTargetApp =
targetApp then unconditionally invoke this.resetSkillsTargetState()),
referencing the symbols targetApp, this.skillsTargetApp, targetChanged, and
resetSkillsTargetState to locate and update the code.

@awsl233777
Copy link
Copy Markdown
Collaborator Author

Closing this PR for now because the branch has merge conflicts and I’m not continuing this line in this PR.

@awsl233777 awsl233777 closed this Apr 3, 2026
@ymkiux ymkiux deleted the chore/web-ui-token-friendly-structure branch April 5, 2026 06:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant