codexmate icon indicating copy to clipboard operation
codexmate copied to clipboard

feat(desktop, analytics): add packaging and usage export

Open awsldev opened this issue 6 months ago • 30 comments

Summary

  • add a Tauri desktop shell for Codex Mate and macOS/Windows packaging
  • publish desktop installer assets directly from the release workflow (.dmg, .msi, .exe) alongside existing npm/standalone archives
  • add analytics usage export for BI/archive workflows via codexmate analytics export and the export-sessions-usage API action
  • support CSV/JSON output, date range filtering, model filtering, and empty-data exports without crashes

Validation

  • npm run test:unit — All 535 tests passed.
  • node --check cli.js
  • node cli.js analytics export --format csv --from 2100-01-01 --to 2100-01-02 --output -
  • node cli.js analytics export --format json --from 2100-01-01 --to 2100-01-02 --output -
  • git diff --check

Notes

  • Local Linux desktop packaging was not run because this machine is missing Rust/Cargo and Linux Tauri system prerequisites (webkit2gtk-4.1, rsvg2). Windows/macOS bundle validation runs through GitHub Actions.
  • The first desktop implementation still expects a system Node runtime. A later hardening pass can bundle a Node sidecar/runtime for fully self-contained desktop installers.
  • The release workflow is workflow_dispatch, so the PR validates its release asset handoff by workflow contract tests and review; a real Release asset upload requires running the release workflow for a tag.

Closes #169 Closes #139

Summary by CodeRabbit

  • New Features

    • macOS and Windows desktop apps with CI-built installers (Windows installer verifies UAC manifest); bundled Node runtime so users need no system Node
    • New CLI/Web API analytics export (CSV/JSON) for session usage
    • Desktop startup diagnostics with optional console output and configurable persistent logs
  • Documentation

    • Desktop staging, build, packaging, debugging, and Windows startup/log guidance added
  • Chores

    • Added desktop npm scripts and CI workflows; raised Node engine to >=16.14.0
  • Tests

    • Added unit tests for desktop staging, analytics export/args, icons, packaging, and release workflow

Review Change Stack

awsldev avatar May 25 '26 10:05 awsldev

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a Tauri desktop shell for Codex Mate with staging, backend startup/shutdown logic, desktop build and release workflow updates, installer hooks, docs, and validation tests.

Changes

Desktop Application with Tauri

Layer / File(s) Summary
Project config and manifests
package.json, .gitignore, src-tauri/.gitignore, src-tauri/Cargo.toml, src-tauri/build.rs, src-tauri/app.manifest, src-tauri/capabilities/default.json, src-tauri/icons/android/*
Adds desktop npm scripts, raises the Node engine floor, adds the Tauri CLI dev dependency, updates ignore rules, sets Cargo package metadata and Rust version, embeds the Windows app manifest in the Tauri build, defines default Tauri capabilities, and adds Android launcher icon resources.
Resource staging script
tools/desktop/prepare-tauri-resources.js
Stages dist/desktop/codexmate, copies runtime entries and production node_modules, bundles the current Node executable, writes codexmate-desktop.json, validates staged resources, and updates Tauri config and Cargo version metadata.
Rust backend lifecycle
src-tauri/src/lib.rs, src-tauri/src/main.rs
Adds desktop diagnostics, logging, readiness checks, stale-port cleanup, Node and CLI resolution, backend spawn and shutdown handling, and the Tauri entrypoint that initializes diagnostics before running the app.
Desktop build and release workflows
.github/workflows/desktop-build.yml, .github/workflows/release.yml, src-tauri/windows/installer-hooks.nsh
Adds a desktop build workflow and updates the release workflow to build, verify, upload, download, and publish desktop artifacts alongside the release process, plus an NSIS preinstall hook.
Tests and docs
tests/unit/desktop-stage.test.mjs, tests/unit/desktop-diagnostics-contract.test.mjs, tests/unit/release-workflow-contract.test.mjs, tests/unit/npm-package-files.test.mjs, tests/unit/run.mjs, doc/desktop.md
Adds contract tests for staging, diagnostics, release workflow patterns, and npm package contents, registers the new tests, and updates desktop documentation for staging, runtime bundling, logging, scripts, and CI behavior.

Sequence Diagram(s)

sequenceDiagram
  participant Developer
  participant StageScript as tools/desktop/prepare-tauri-resources.js
  participant DesktopBuild as .github/workflows/desktop-build.yml
  participant ReleaseWorkflow as .github/workflows/release.yml
  participant TauriRuntime as src-tauri/src/main.rs + lib.rs

  Developer->>StageScript: npm run desktop:stage
  StageScript->>StageScript: copy runtime entries, node_modules, node-runtime
  DesktopBuild->>DesktopBuild: build and verify Windows manifest
  DesktopBuild->>DesktopBuild: upload desktop artifacts
  ReleaseWorkflow->>ReleaseWorkflow: resolve, download artifacts, publish installers
  TauriRuntime->>TauriRuntime: init_desktop_diagnostics() and run()

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Suggested reviewers

  • ymkiux

Poem

🐇 I hop through scripts and Tauri dreams, Staging bundles, logs, and release streams. A Windows manifest stands bold and bright, While desktop builds bundle up just right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the two main themes of the PR: desktop packaging and analytics usage export.
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.

✏️ 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 pr-168

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[bot] avatar May 25 '26 10:05 coderabbitai[bot]

Updated this PR after rebasing onto latest main and replacing the direct Tauri resource mapping with a staged desktop runtime layout.

Validation run locally:

  • npm run desktop:stage ✅
  • node tests/unit/run.mjs ✅ All 532 tests passed
  • npm run lint ✅ 303 files passed
  • npm pack --dry-run --json ✅ verified no src-tauri/, tools/desktop/, or dist/ in the npm CLI package
  • npm run test:e2e ✅
  • npm run desktop:build attempted locally, but this host has no Rust/Cargo (cargo metadata ... No such file or directory), so native bundle validation is left to the GitHub Actions macOS/Windows desktop-build jobs.

@coderabbitai review

awsldev avatar May 26 '26 07:05 awsldev

@awsl233777 Thanks for the detailed validation summary! Triggering a full review of the updated PR now. 🐇

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 26 '26 07:05 coderabbitai[bot]

Updated the desktop app icons from site/.vitepress/public/images/logo-v.png using npx tauri icon.

Validation run locally:

  • npm run desktop:stage ✅
  • node tests/unit/run.mjs ✅ All 532 tests passed

Notes:

  • The generated icon set updates the configured Tauri bundle icons: 32x32.png, 128x128.png, [email protected], icon.icns, and icon.ico.
  • The generator also produced the additional Tauri platform icon assets under src-tauri/icons/, including Appx, iOS, and Android sizes.

@coderabbitai re-review

awsldev avatar May 26 '26 10:05 awsldev

@awsl233777 Thanks for the icon update! The generated set covers all required Tauri targets (macOS .icns, Windows .ico, and standard PNG sizes) as well as the extra platform assets. Triggering a full re-review now. 🐇

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 26 '26 10:05 coderabbitai[bot]

兔子审查 - 必须修复的问题

🔴 Critical (安全/资源泄漏)

1. .github/workflows/desktop-build.yml - Actions 未固定 + 凭证持久化

zizmor 标记风险:

  • ❌ 使用浮动引用 @v4 而非固定 commit SHA
  • ❌ checkout 缺少 persist-credentials: false

修复:

- uses: actions/checkout@11bd71901bb5bfa8cfe5dfc19f1acec4b1441d73
  with:
    persist-credentials: false

2. src-tauri/src/lib.rs:116-122 - 子进程泄漏

问题:wait_for_backend 超时后,spawn 的 Node.js 进程变成孤儿进程

修复:

let mut child = command  // 改为 mut
    .spawn()
    .map_err(|err| format!("unable to start codexmate backend with Node.js: {err}"))?;

if !wait_for_backend(Duration::from_secs(15)) {
    let _ = child.kill();
    let _ = child.wait();
    return Err("codexmate backend did not become ready on 127.0.0.1:3737".into());
}

3. src-tauri/src/lib.rs:39-44 - 健康检查误判

问题:只检查 HTTP 200,3737 端口任何服务都会通过

修复:验证 backend 特定响应

let status_ok = response.starts_with("HTTP/1.1 200") || response.starts_with("HTTP/1.0 200");
let identity_ok = response.contains("\"ok\":true");
status_ok && identity_ok

4. src-tauri/tauri.conf.json:26-28 - CSP 被禁用

问题:"csp": null 移除了 webview 注入保护

修复:

"security": {
  "csp": "default-src 'self' http://127.0.0.1:3737; connect-src 'self' http://127.0.0.1:3737; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'"
}

5. tools/desktop/prepare-tauri-resources.js:48-53 - Node 版本冲突

问题:fs.cpSync 需要 Node ≥16,但 package.json 声明 >=14

修复(二选一):

  • A 提升 engines:"engines": { "node": ">=16.14.0" }
  • B 用兼容实现替换 fs.cpSync

🟡 Nice to Have

6. tests/unit/desktop-stage.test.mjs:54-56 - 脆弱断言

改用属性检查而非全对象相等

ymkiux avatar May 27 '26 03:05 ymkiux

@coderabbitai re-review

I addressed the findings from https://github.com/SakuraByteCore/codexmate/pull/172#issuecomment-4550927315 in commit 6242a2b:

  • Pinned the desktop workflow actions to commit SHAs and set actions/checkout persist-credentials: false.
  • Kill and wait for the spawned backend process when desktop startup readiness times out.
  • Tightened the desktop backend health check to require both HTTP 200 and the Codex Mate {"ok":true} health response.
  • Replaced the disabled Tauri CSP with a restricted policy and made the desktop staging script preserve that CSP.
  • Raised the Node engine requirement to >=16.14.0 in package.json and package-lock.json to match fs.cpSync usage.
  • Replaced the brittle desktop staging resource deep-equality assertion with targeted property checks and added CSP assertions.

Validation actually run:

npm run test:unit
All 532 tests passed.

Local limitation: this environment does not have cargo, so Rust fmt/check must be covered by CI.

Could you please verify whether the previously listed issues are now resolved?

awsldev avatar May 27 '26 06:05 awsldev

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== 1. .github/workflows/desktop-build.yml ==="
cat .github/workflows/desktop-build.yml

echo ""
echo "=== 2 & 3. src-tauri/src/lib.rs ==="
cat src-tauri/src/lib.rs

echo ""
echo "=== 4. src-tauri/tauri.conf.json ==="
cat src-tauri/tauri.conf.json

echo ""
echo "=== 5. package.json (engines) ==="
python3 -c "import json; d=json.load(open('package.json')); print('engines:', d.get('engines')); print('devDeps tauri:', d.get('devDependencies',{}).get('`@tauri-apps/cli`'))"

echo ""
echo "=== 6. tests/unit/desktop-stage.test.mjs ==="
cat tests/unit/desktop-stage.test.mjs

Length of output: 10697



@awsl233777 All six issues from the previous review have been confirmed resolved in commit 6242a2b. Here's the verification summary:

# Issue Status
1 Workflow actions pinned + persist-credentials: false ✅ All four actions (checkout, setup-node, rust-toolchain, upload-artifact) are pinned to full commit SHAs; persist-credentials: false is set.
2 Child process kill on backend readiness timeout ✅ child is now mut; child.kill() + child.wait() are called when wait_for_backend returns false.
3 Health-check identity verification ✅ Requires both HTTP 200 (status_ok) and "ok":true in the response body (identity_ok).
4 CSP no longer disabled ✅ "csp" is set to a restrictive policy (default-src 'self' http://127.0.0.1:3737; connect-src ...; img-src ...; style-src ...; script-src 'self') instead of null.
5 Node engine requirement raised to >=16.14.0 ✅ package.json engines.node is ">=16.14.0".
6 Brittle deep-equality assertion replaced ✅ The test now uses targeted assert.strictEqual / assert.ok / assert.match checks, including explicit CSP pattern assertions.

The only remaining item (Rust fmt/clippy checks) is correctly deferred to the CI environment — that's expected given the local cargo constraint. Everything looks good. 🐇 ✨

✅ Actions performed

Full review triggered.

coderabbitai[bot] avatar May 27 '26 06:05 coderabbitai[bot]

@coderabbitai re-review

Follow-up on the remaining desktop review item:

  • Restricted the current_dir.join("cli.js") fallback to debug builds only with #[cfg(debug_assertions)], so release builds only use bundled resource paths.

Latest validation actually run after this change:

npm run test:unit
All 532 tests passed.

The prior six items from https://github.com/SakuraByteCore/codexmate/pull/172#issuecomment-4550927315 remain addressed, and CI on the previous head was green before this follow-up commit. Please verify whether the remaining review concern is now resolved on the latest head.

awsldev avatar May 27 '26 06:05 awsldev

Your plan includes 2 PR reviews per hour. More reviews will be available in 19 minutes and 40 seconds.

coderabbitai[bot] avatar May 27 '26 06:05 coderabbitai[bot]

@coderabbitai re-review

Follow-up release packaging change in b13f13a:

  • Split the release workflow into resolve, desktop, and release jobs.
  • Build macOS and Windows Tauri installers during release.
  • Upload only installer-friendly desktop outputs from the desktop jobs:
    • *.dmg
    • *.msi
    • *.exe
  • Download those desktop artifacts in the release job and attach them directly as GitHub Release assets alongside the existing npm .tgz and standalone .tar.gz artifacts.
  • Added a unit contract test so the release workflow keeps attaching desktop installer assets instead of regressing to Actions artifact-only output.
  • Pinned the newly touched release workflow actions to commit SHAs and disabled checkout credential persistence.

Validation actually run:

npm run test:unit
All 533 tests passed.

git diff --check
(no output)

Please verify the latest head, especially the release workflow artifact handoff and release asset globs.

awsldev avatar May 27 '26 06:05 awsldev

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== Release workflow ==="
fd -e yml -e yaml . .github/workflows/ --exec cat {}

echo ""
echo "=== Desktop build workflow ==="
cat .github/workflows/desktop-build.yml 2>/dev/null || echo "not found"

echo ""
echo "=== Unit test files (new contract test) ==="
fd 'release' tests/unit/ 2>/dev/null || fd '\.test\.mjs$' tests/unit/ | sort

echo ""
echo "=== tests/unit/run.mjs ==="
cat tests/unit/run.mjs

echo ""
echo "=== All test mjs files listing ==="
fd '\.test\.mjs$' tests/unit/ | sort

Length of output: 25332


🏁 Script executed:

#!/bin/bash
# Read any new release-related test files
echo "=== release workflow contract test (if any) ==="
fd 'release' tests/unit/ 2>/dev/null
fd 'release' tests/ 2>/dev/null

echo ""
echo "=== Newer test files ==="
ls -la tests/unit/

echo ""
echo "=== package.json scripts section ==="
python3 -c "import json; d=json.load(open('package.json')); [print(k,'=',v) for k,v in d.get('scripts',{}).items()]"

echo ""
echo "=== package.json engines ==="
python3 -c "import json; d=json.load(open('package.json')); print(d.get('engines'))"

Length of output: 7351


🏁 Script executed:

#!/bin/bash
echo "=== release-workflow-contract.test.mjs ==="
cat tests/unit/release-workflow-contract.test.mjs

echo ""
echo "=== Checking ci.yml for unpinned actions ==="
cat .github/workflows/ci.yml

echo ""
echo "=== Release workflow: softprops action SHA verification ==="
grep -n "softprops\|download-artifact\|upload-artifact\|checkout\|setup-node\|rust-toolchain" .github/workflows/release.yml

Length of output: 3519



@awsl233777 Verified commit b13f13a. Here's the full check:

# Item Status
1 resolve → desktop → release job split ✅ Three jobs confirmed; desktop needs resolve, release needs both.
2 Desktop installer upload globs ✅ Desktop job uploads bundle/dmg/*.dmg, bundle/msi/*.msi, bundle/nsis/*.exe with if-no-files-found: error.
3 Artifact download → release asset handoff ✅ Release job downloads via pattern: codexmate-desktop-*, merge-multiple: true into desktop-release-assets/, then attaches `desktop-release-assets/**/*.dmg
4 All actions pinned to commit SHAs ✅ All six actions in release.yml (checkout, setup-node, rust-toolchain, upload-artifact, download-artifact, softprops/action-gh-release) are pinned to full SHAs.
5 persist-credentials: false ✅ All three checkout steps (resolve, desktop, release jobs) have it set.
6 Unit contract test registered ✅ tests/unit/release-workflow-contract.test.mjs exists and is imported in run.mjs. It asserts the full pipeline: job ordering, matrix usage, all three upload globs, download pattern, merge-multiple: true, and all three release asset globs.

One minor pre-existing note (out of scope for this PR): .github/workflows/ci.yml still uses floating actions/checkout@v4 and actions/setup-node@v4 references — that workflow was not modified here, so it's not a blocker, but worth a follow-up hardening pass.

Everything in scope for this PR looks solid. 🐇 ✨

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 27 '26 06:05 coderabbitai[bot]

@coderabbitai re-review

Follow-up for #139 in 948fdd3:

  • Added analytics usage export support via codexmate analytics export.
  • Added export-sessions-usage API action for UI/API consumers.
  • Exports rows grouped by UTC date + model with columns/fields: date, model, tokens, sessions.
  • Supports --format csv|json, --from, --to, --model, --source, --output, and --force-refresh.
  • Handles empty data gracefully:
    • CSV emits only date,model,tokens,sessions header.
    • JSON emits { "rows": [] }.
  • Added backend tests for CSV/JSON export, model/date filtering, and empty exports.
  • Updated PR title/body and added Closes #139.

Validation actually run:

npm run test:unit
All 535 tests passed.

node --check cli.js

node cli.js analytics export --format csv --from 2100-01-01 --to 2100-01-02 --output -
date,model,tokens,sessions

node cli.js analytics export --format json --from 2100-01-01 --to 2100-01-02 --output -
{
  "rows": []
}

git diff --check
(no output)

Please review the latest analytics export implementation and the PR metadata update.

awsldev avatar May 27 '26 06:05 awsldev

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== Find analytics-related files changed in 948fdd3 ==="
git show --stat 948fdd3 2>/dev/null | head -60

echo ""
echo "=== Find analytics export implementation files ==="
fd -e js -e mjs analytics . --exclude node_modules | sort

echo ""
echo "=== Find export-sessions-usage or analytics export in codebase ==="
rg -rn "export-sessions-usage\|analytics.*export\|exportSessions\|export_sessions" --type js -l 2>/dev/null | head -20

Length of output: 1100


🏁 Script executed:

#!/bin/bash
echo "=== Show all files changed in 948fdd3 ==="
git diff --name-only 948fdd3^ 948fdd3 2>/dev/null || git show --name-only --format="" 948fdd3 2>/dev/null | head -40

echo ""
echo "=== git log last 3 commits ==="
git log --oneline -5 2>/dev/null

Length of output: 715


🏁 Script executed:

#!/bin/bash
echo "=== cli/session-usage.js (full) ==="
cat cli/session-usage.js

echo ""
echo "=== cli.js analytics export section (diff only) ==="
git show 948fdd3 -- cli.js | head -200

echo ""
echo "=== tests/unit/session-usage-backend.test.mjs ==="
cat tests/unit/session-usage-backend.test.mjs

Length of output: 66252



@awsl233777 Reviewed commit 948fdd3. The analytics export implementation is well-structured and the core logic is sound. Here's the full breakdown:


✅ Confirmed working correctly

Item Notes
Date filtering parseUsageExportDate is UTC-safe; boundary 'end' adds 24 h via Date.UTC, correctly handles DST
from === to same-day fromTime < toTime (24 h apart), not an error — returns empty results as expected
CSV escaping escapeUsageCsvCell quotes cells containing ,, ", \n, \r per RFC 4180
Empty export CSV emits header-only; JSON emits {"rows":[]} — both verified by new tests
Model filter substring match model.includes(filter) allows partial matches like gpt-5.3 matching gpt-5.3-codex
API export-sessions-usage Source validation before delegating; date/model filters from usageParams pass through; listSessionUsageCore caps limit at MAX_SESSION_USAGE_LIST_SIZE
Test quality Two new tests use direct usageCore.* calls — no brittle function-extraction, good coverage of CSV/JSON/filtering/empty paths

🟡 Minor issues worth noting

1. CSV line endings — LF instead of CRLF serializeUsageExportRowsToCsv joins lines with \n. RFC 4180 §2 requires CRLF. Windows Excel may render the entire file as a single column when opened directly.

// cli/session-usage.js
return lines.join('\r\n') + '\r\n';  // RFC 4180-compliant

2. -o shorthand not documented in help text parseAnalyticsExportArgs accepts -o as an alias for --output, but printAnalyticsUsage doesn't mention it.

// cli.js — printAnalyticsUsage
console.log('  codexmate analytics export ... [--output <PATH|->] [-o <PATH|->]  ...');

3. params.modelType in normalizeUsageExportModelFilters is undocumented The function reads params.modelType as an additional model filter source but it's not exposed in the CLI flags or help. This is probably an API-facing alias but worth a comment.

4. No unit test for parseAnalyticsExportArgs The argument parser has several branches (unknown tokens, --format validation, --source validation, =-style args). These are untested. A few targeted tests for the error paths would help.


🔴 Scope concern

Commit 948fdd3 adds a full analytics export feature (for issue #139) to PR #172, which is scoped to desktop packaging (issue #169). These are completely independent features with no shared code paths. It would be cleaner to split this into its own PR so the desktop changes can be merged/reviewed independently. That said, if the intent is to land both together, there are no correctness blockers in the analytics implementation.


Summary: The analytics export logic is correct and the tests are solid. The main actionable items are CSV CRLF line endings (Windows compatibility), the undocumented -o alias, and the scope question. The desktop-specific changes from prior commits remain unaffected.

coderabbitai[bot] avatar May 27 '26 07:05 coderabbitai[bot]

@coderabbitai re-review

I pushed commit c621391 to address the actionable items from your review comment on 948fdd3:

  • changed analytics CSV export line endings from LF to RFC 4180 CRLF
  • documented the -o shorthand in both analytics export help and top-level help
  • added an explanatory comment for the API-facing modelType filter alias
  • moved parseAnalyticsExportArgs into a small testable module and added focused parser tests for shorthand, --flag=value, help, unknown args, and invalid choices

Verified locally:

  • npm run test:unit → All 538 tests passed.
  • npm run lint → Lint passed for 307 file(s).
  • git diff --check → passed

Please confirm whether this latest commit really resolves the issues from your comment, especially the CSV CRLF behavior, -o help coverage, modelType documentation, and parser test coverage. If you still see a problem, please point to the remaining specific blocker.

awsldev avatar May 27 '26 16:05 awsldev

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== 1. CSV line endings in session-usage.js ==="
grep -n "join\|CRLF\|\\\\r\\\\n\|\\\\n" cli/session-usage.js | head -20

echo ""
echo "=== 2. -o shorthand in help text ==="
grep -n "\-o\|output\|shorthand" cli.js | grep -i "analytic\|export\|\-o" | head -20

echo ""
echo "=== 3. modelType comment ==="
grep -n "modelType\|model_type\|API-facing\|alias" cli/session-usage.js | head -15

echo ""
echo "=== 4. parseAnalyticsExportArgs module location ==="
fd "parse.*export\|export.*args\|analytics.*args" . --exclude node_modules | sort
fd "analytics-export\|analytics_export\|parseAnalytics" . --exclude node_modules | sort

echo ""
echo "=== 5. New test files for parser ==="
fd '\.test\.mjs$' tests/unit/ | sort

echo ""
echo "=== 6. run.mjs to confirm new test registered ==="
cat tests/unit/run.mjs

Length of output: 10970


🏁 Script executed:

#!/bin/bash
echo "=== Top-level analytics help section ==="
grep -n "analytics\|export\|\-o\b" cli.js | grep -v "//.*-o\b" | grep -i "analytics\|export" | head -30

echo ""
echo "=== analytics-export-args test content ==="
cat tests/unit/analytics-export-args.test.mjs

Length of output: 4476



@awsl233777 Verified commit c621391. All four items are confirmed resolved:

# Item Status
1 CSV CRLF line endings ✅ lines.join('\r\n') + '\r\n' at Line 212 of cli/session-usage.js — RFC 4180-compliant.
2 -o shorthand documented ✅ Analytics export help (Line 9808 of cli.js) now shows `[--output <PATH
3 modelType alias comment ✅ Lines 181–183 of cli/session-usage.js have // API-facing alias: callers may pass modelType when they reuse usage filters.
4 parseAnalyticsExportArgs parser tests ✅ tests/unit/analytics-export-args.test.mjs is registered in run.mjs and covers: --flag=value style args, -o shorthand, --help, unknown token errors, and invalid --format/--source choice errors.

Everything looks solid. 🐇 ✨


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

coderabbitai[bot] avatar May 27 '26 16:05 coderabbitai[bot]

@coderabbitai re-review

Follow-up commit e91b464 adds a desktop icon contract test after manually verifying the Tauri icon chain:

  • asserts src-tauri/tauri.conf.json bundle.icon references the desktop icons Tauri should consume:
    • icons/32x32.png
    • icons/128x128.png
    • icons/[email protected]
    • icons/icon.icns
    • icons/icon.ico
  • asserts the generated PNG sizes for the desktop and Windows Store icon files
  • parses icon.ico and confirms it contains 16/24/32/48/64/256 px entries
  • parses icon.icns and confirms it contains the expected macOS ICNS entries (ic07 through ic14 plus 16/32 mask entries)

Verified locally after the test addition:

  • targeted desktop-stage tests passed
  • npm run test:unit → All 539 tests passed.
  • npm run lint → Lint passed for 307 file(s).
  • git diff --check → passed

Please confirm whether the previous desktop icon distribution is correct across the generated sizes and whether the icons are truly used by the Tauri desktop bundle configuration. If there is still an icon packaging/usage gap, please point to the exact missing platform, size, or config path.

awsldev avatar May 27 '26 16:05 awsldev

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== 1. tauri.conf.json bundle.icon section ==="
python3 -c "import json; d=json.load(open('src-tauri/tauri.conf.json')); print(json.dumps(d.get('bundle',{}).get('icon','NOT FOUND'), indent=2))"

echo ""
echo "=== 2. New icon contract test file (if present) ==="
fd 'icon' tests/unit/ | sort
fd 'icon.*contract\|contract.*icon\|desktop.*icon\|icon.*test' tests/unit/ | sort
# List all test files to find new ones
ls -la tests/unit/

echo ""
echo "=== 3. run.mjs ==="
cat tests/unit/run.mjs

echo ""
echo "=== 4. Icon files present under src-tauri/icons/ ==="
find src-tauri/icons/ -type f | sort

echo ""
echo "=== 5. Read the newest test file content ==="
fd '\.test\.mjs$' tests/unit/ | sort | xargs ls -la

Length of output: 20157


🏁 Script executed:

#!/bin/bash
echo "=== desktop-stage.test.mjs (full) ==="
cat tests/unit/desktop-stage.test.mjs

echo ""
echo "=== Check if run.mjs has any new imports vs expected ==="
grep -c "import" tests/unit/run.mjs

echo ""
echo "=== Check icon file binary headers to verify they're real PNGs, ICO, ICNS ==="
python3 - <<'EOF'
import struct, os

icons_dir = "src-tauri/icons"

# Check key PNGs have correct PNG header
for name in ["32x32.png","128x128.png","[email protected]","icon.png","64x64.png"]:
    p = os.path.join(icons_dir, name)
    with open(p,"rb") as f:
        hdr = f.read(8)
        ok = hdr == b'\x89PNG\r\n\x1a\n'
        print(f"PNG {name}: {'OK' if ok else 'BAD'}")

# Check ICO header
ico_path = os.path.join(icons_dir, "icon.ico")
with open(ico_path,"rb") as f:
    data = f.read()
    reserved, img_type, count = struct.unpack_from("<HHH", data, 0)
    print(f"\nICO reserved={reserved}, type={img_type}, count={count}")
    sizes = []
    for i in range(count):
        off = 6 + i * 16
        w, h = data[off], data[off+1]
        sizes.append(w if w != 0 else 256)
    print(f"ICO sizes (width): {sorted(sizes)}")

# Check ICNS header
icns_path = os.path.join(icons_dir, "icon.icns")
with open(icns_path,"rb") as f:
    data = f.read()
    magic = data[:4]
    total_len = struct.unpack_from(">I", data, 4)[0]
    print(f"\nICNS magic={magic}, declared_len={total_len}, file_len={len(data)}")
    # Read all block type tags
    offset = 8
    tags = []
    while offset < len(data) - 8:
        tag = data[offset:offset+4].decode('ascii', errors='replace')
        blk_len = struct.unpack_from(">I", data, offset+4)[0]
        tags.append(tag)
        if blk_len < 8: break
        offset += blk_len
    print(f"ICNS block tags: {tags}")
EOF

Length of output: 8269



@awsl233777 Verified commit e91b464. All icon contract assertions are confirmed correct against the actual binary files.

# Item Status
1 bundle.icon references in tauri.conf.json ✅ Exactly the 5 expected paths: icons/32x32.png, icons/128x128.png, icons/[email protected], icons/icon.icns, icons/icon.ico
2 All 5 bundle icon files physically present ✅ All confirmed in src-tauri/icons/
3 PNG headers and dimensions ✅ All 15 named PNGs (desktop sizes + all Windows Store Square*Logo.png + StoreLogo.png) have valid \x89PNG magic; readPngSize correctly reads from the IHDR chunk at offset 16/20
4 ICO entries ✅ reserved=0, type=1, 6 images at [16, 24, 32, 48, 64, 256] — exactly matches the test assertion
5 ICNS blocks ✅ Magic icns, declared_len == file_len (2,545,705 bytes), block tags sorted: ['ic07','ic08','ic09','ic10','ic11','ic12','ic13','ic14','il32','is32','l8mk','s8mk'] — exact match
6 Test registered ✅ Icon contract test lives in desktop-stage.test.mjs (already imported in run.mjs)

No icon packaging or config gap. The icon chain is complete and the binary file assertions are accurate. 🐇 ✨

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 27 '26 16:05 coderabbitai[bot]

@coderabbitai re-review

Follow-up commit 90cab7f addresses Windows MSI startup crash debugging by making the desktop executable self-diagnosing instead of requiring users to manually dig through Event Viewer.

What changed:

  • codexmate-desktop.exe --debug-console enables Windows console diagnostics for release builds.
  • CODEXMATE_DESKTOP_LOG=1 enables the same mode through environment variables.
  • CODEXMATE_DESKTOP_LOG_FILE=<path> can override the log file location.
  • Windows release builds keep the GUI subsystem for normal double-click behavior, but debug mode tries to AttachConsole(ATTACH_PARENT_PROCESS) and writes console output through CONOUT$ as a fallback.
  • Desktop startup, backend spawn, backend readiness timeout, backend stop, and Rust panics are logged.
  • The bundled Node backend no longer drops logs:
    • debug console mode inherits stdout/stderr
    • normal GUI mode appends backend stdout/stderr to %LOCALAPPDATA%\\CodexMate\\logs\\desktop.log
  • Added docs in doc/desktop.md and a source contract test in tests/unit/desktop-diagnostics-contract.test.mjs.

Verified locally:

  • targeted desktop diagnostics/stage tests passed
  • npm run test:unit → All 541 tests passed.
  • npm run lint → Lint passed for 308 file(s).
  • git diff --check → passed

Local blocker: this machine does not have cargo, so Rust compile validation is intentionally left to GitHub Actions Windows/macOS desktop-build checks.

Please check whether this approach is correct for Tauri Windows release diagnostics and whether there are any remaining concerns with console attachment, backend stdio inheritance, file logging, or normal double-click UX.

awsldev avatar May 28 '26 02:05 awsldev

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== src-tauri/src/lib.rs ==="
cat src-tauri/src/lib.rs

echo ""
echo "=== tests/unit/desktop-diagnostics-contract.test.mjs ==="
cat tests/unit/desktop-diagnostics-contract.test.mjs

echo ""
echo "=== doc/desktop.md ==="
cat doc/desktop.md

echo ""
echo "=== tests/unit/run.mjs (confirm new test registered) ==="
cat tests/unit/run.mjs

echo ""
echo "=== src-tauri/src/main.rs ==="
cat src-tauri/src/main.rs

Length of output: 19421



@awsl233777 Reviewed commit 90cab7f. The overall approach is sound. Here's the full check:

# Item Status
1 AttachConsole(ATTACH_PARENT_PROCESS) + SAFETY comment ✅ extern "system" via #[link(name = "kernel32")], constant 0xFFFF_FFFF, SAFETY documented.
2 CONOUT$ fallback ✅ Inside #[cfg(windows)] only; falls through to stderr on non-Windows and when no console is attached.
3 Normal double-click UX unaffected ✅ No args/env → desktop_debug_requested() = false → DESKTOP_CONSOLE_LOGGING = false → CREATE_NO_WINDOW applied → no black console.
4 Backend stdio in debug mode ✅ Stdio::inherit() for both stdout/stderr when DESKTOP_CONSOLE_LOGGING is true.
5 Backend stdio in normal GUI mode ✅ Both streams redirected to desktop_log_stdio() (append to desktop.log).
6 File logging always active ✅ desktop_log() writes to file regardless of console logging flag — useful for post-mortem even without debug mode.
7 Panic hook ✅ std::panic::set_hook captures panics to the log file.
8 init_desktop_diagnostics() called before run() ✅ main.rs calls init_desktop_diagnostics() first; it is exported as pub.
9 Contract tests ✅ Both tests registered in run.mjs, covering all env vars/flags, AttachConsole, CONOUT$, log path, panic hook, stdio inheritance, CREATE_NO_WINDOW guard.

🟡 Minor items (non-blocking)

1. desktop_log_stdio() called twice → two file handles on the same path

command.stdout(desktop_log_stdio()).stderr(desktop_log_stdio());

Both calls open the log file with append(true). On Windows, Rust's OpenOptions sets FILE_SHARE_READ | FILE_SHARE_WRITE by default, so there's no sharing violation. However, two concurrent append handles can interleave partial writes if Node writes to both stdout and stderr simultaneously. In practice, low-volume startup logs make this a non-issue, but if you want belt-and-suspenders safety you could open once and clone the handle:

let log_stdio_out = desktop_log_stdio();
let log_stdio_err = desktop_log_stdio(); // separate append handle is fine for low-volume
command.stdout(log_stdio_out).stderr(log_stdio_err);

(No change actually needed — current code is fine for this use case.)

2. Raw epoch-ms timestamps are hard to read directly

Log lines like [1748000000000] backend spawned require external conversion. If you ever want human-readable output, replacing with an ISO 8601 formatter (even a simple YYYY-MM-DDTHH:MM:SSZ via SystemTime) would help. Not required for diagnostics but nice for usability.


Edge-case worth documenting (already implied by the docs): If a user runs codexmate-desktop.exe --debug-console by double-clicking (no parent console), AttachConsole returns 0 → DESKTOP_CONSOLE_LOGGING stays false → no console output appears, but the file log at %LOCALAPPDATA%\CodexMate\logs\desktop.log still captures everything. The doc's "尝试附着父控制台" wording correctly sets the expectation. ✅

Everything critical is correct. The diagnostics chain (env → console attach → CONOUT$ → file log → backend stdio → panic hook) is complete and the contract tests protect the key paths. 🐇 ✨

coderabbitai[bot] avatar May 28 '26 02:05 coderabbitai[bot]