Skip to content

chore: update to zig 0.16 and zigzag v0.1.5 - #3

Merged
midasdf merged 10 commits into
masterfrom
claude/update-sshz-zig-0.16-EDHxe
May 7, 2026
Merged

midasdf merged 10 commits into
masterfrom
claude/update-sshz-zig-0.16-EDHxe

Conversation

@midasdf

@midasdf midasdf commented May 7, 2026 •

Copy link
Copy Markdown
Owner

User description

Migrates sshz to Zig 0.16's reworked I/O model, where filesystem,
process, and network operations require an Io instance. The main
entry point now takes std.process.Init, and io plus environ_map
are threaded through ssh_config, meta, app, and checker.

Notable changes:

  • main: std.process.spawn(io, ...) replaces std.process.Child.init
  • main: std.Io.File.stdout() replaces std.fs.File{ .handle = ... }
  • main: init.minimal.args.toSlice(arena) replaces argsAlloc/argsFree
  • ssh_config/meta: switch to std.Io.Dir.cwd() with buffered writers
    and init.environ_map.get("HOME") for env access
  • checker: use std.Io.net.HostName.connect(io, port, .{}) for TCP
    status checks
  • views: zz.Color.cyan/white are now consts (not functions)
  • CI: install Zig 0.16.0
  • build.zig.zon: bump zigzag to v0.1.5, set minimum_zig_version

Note: the zigzag dependency hash needs to be regenerated with
zig fetch --save=zigzag <url> against a real Zig 0.16 toolchain;
the current value in build.zig.zon is the v0.1.2 hash and will be
rejected at build time.


CodeAnt-AI Description

Make sshz work with Zig 0.16 and keep saved data features working

What Changed

  • Updated sshz to run on Zig 0.16, so the app can build and start with the newer toolchain
  • Kept reading and saving SSH config and connection history working with the newer runtime
  • Kept status checks and “last connected” times working after the Zig update
  • Updated the CI build to use Zig 0.16

Impact

✅ Builds with Zig 0.16
✅ Fewer startup failures after toolchain updates
✅ Connection history and host status stay available

🔄 Retrigger CodeAnt AI Review

Details

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

リリースノート

  • Chores

    • Zig コンパイラを 0.15.2 → 0.16.0 に更新しました。
    • zigzag 依存を v0.1.2 → v0.1.5 に更新しました。
    • リポジトリで zig-pkg/ を無視するよう.gitignoreを更新しました。
  • Bug Fixes / 信頼性向上

    • ファイル入出力をより堅牢にし、書き込みを一時ファイル経由で原子的に置換・バックアップするよう改善しました(失敗時は安全にスキップ)。
  • UI

    • 「最終接続時刻」の表示が正確かつ安定して相対時刻で表示されるようになりました。

claude added 6 commits May 7, 2026 07:16
Migrates sshz to Zig 0.16's reworked I/O model, where filesystem,
process, and network operations require an `Io` instance. The main
entry point now takes `std.process.Init`, and `io` plus `environ_map`
are threaded through ssh_config, meta, app, and checker.

Notable changes:
- main: `std.process.spawn(io, ...)` replaces `std.process.Child.init`
- main: `std.Io.File.stdout()` replaces `std.fs.File{ .handle = ... }`
- main: `init.minimal.args.toSlice(arena)` replaces `argsAlloc/argsFree`
- ssh_config/meta: switch to `std.Io.Dir.cwd()` with buffered writers
  and `init.environ_map.get("HOME")` for env access
- checker: use `std.Io.net.HostName.connect(io, port, .{})` for TCP
  status checks
- views: `zz.Color.cyan`/`white` are now consts (not functions)
- CI: install Zig 0.16.0
- build.zig.zon: bump zigzag to v0.1.5, set minimum_zig_version

Note: the zigzag dependency hash needs to be regenerated with
`zig fetch --save=zigzag <url>` against a real Zig 0.16 toolchain;
the current value in build.zig.zon is the v0.1.2 hash and will be
rejected at build time.
- readFileAlloc takes (io, sub_path, gpa, limit) not (io, gpa, sub_path, limit)
- rename uses method call style: dir.rename(old_path, new_dir, new_path, io)
- Unmanaged std.ArrayList no longer has default field values, so .{}
  initialization fails; switch to .empty
- std.Thread.Mutex is gone; use std.Io.Mutex with lockUncancelable(io)
  and unlock(io)
- ResultQueue now also takes an Io instance so its mutex can lock
- build.zig.zon: use real v0.1.5 hash from zig fetch
- app.zig: ArrayList(...).empty (not .{}) for new unmanaged ArrayList
- checker.zig: pass .mode = .stream for HostName.connect
- meta.zig/utils.zig/ssh_config.zig: route io through for the new
  std.Io.Timestamp.now(.real) clock API
- tests/test_meta.zig: pass std.testing.io to recordConnection

Verified locally: zig 0.16.0 builds the exe, all 29 tests pass,
and zig fmt --check src/ is clean.
@codeant-ai

codeant-ai Bot commented May 7, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Rate limit exceeded

@midasdf has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 20 minutes and 49 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e5021ecf-fa7e-4ebf-8ad1-9c34fb150801

📥 Commits

Reviewing files that changed from the base of the PR and between 3f625e2 and b9ba2b5.

📒 Files selected for processing (5)
  • src/app.zig
  • src/meta.zig
  • src/ssh_config.zig
  • src/views/host_list.zig
  • tests/test_ssh_config.zig
📝 Walkthrough

Walkthrough

Zig を 0.16.0 に上げ、std.Io と std.process.Init を注入してファイルIO・プロセス生成・スレッド同期・タイムスタンプ取得を IO 経由で一元化するリファクタリングです。

変更内容

Zig 0.16.0 と IO 統合リファクタリング

Layer / File(s) Summary
ビルドと CI 設定
.github/workflows/ci.yml, .gitignore, build.zig.zon
Zig を 0.15.2 から 0.16.0 へ更新、zigzag を v0.1.5 に更新し、zig-pkg/ を .gitignore に追加。
コア型シグネチャの更新
src/app.zig, src/checker.zig, src/utils.zig
Model に io と env フィールド追加。ResultQueue/StatusChecker の init に io 追加。relativeTimeFromTimestamp が io を受け取るよう変更。
チェッカー同時実行の IO 化
src/checker.zig
ResultQueue と StatusChecker が std.Io.Mutex と lockUncancelable を使用、tcpCheck が io を受け取り IO 経由で接続を行うよう変更。
メタストア実装と IO 統合
src/meta.zig
readFile/writeFile が std.Io.Dir.cwd() と一時ファイル+原子的リネームで実装、recordConnection が Io.Timestamp.now(io, .real) を使用、defaultMetaPath/defaultBackupDir が環境マップを参照。
SSH 設定の IO 化とバックアップ
src/ssh_config.zig
readFile/writeFile/backupFile/rotateBackups が std.Io 対応となり、openDir/createFile/rename を利用する実装に変更。defaultConfigPath が環境マップ対応。
Model 初期化と統合
src/app.zig
Model が io と env を格納。初期化で ssh_config と meta を io 経由で読み込み、接続記録・保存・削除で io ベースの writeFile を使用。
メインエントリポイントと Process 統合
src/main.zig
main が std.process.Init を受け取り、launchTui/directConnect が init コンテキストを使用。SSH 実行が std.process.spawn(io, ...) と child.wait(io) に変更。
UI ビューの IO 対応
src/views/forward.zig, src/views/help.zig, src/views/host_form.zig, src/views/host_list.zig
renderHostLine が io パラメータを受け取り relativeTimeFromTimestamp(io, ...) を呼び出すように変更。ArrayList 初期化を .empty に統一し、カラー呼び出し構文の統一。
テストと実装完成
tests/test_meta.zig
recordConnection 呼び出しに std.testing.io パラメータを追加。

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR title accurately describes the main changes: upgrading to Zig 0.16 and zigzag v0.1.5 dependency, which are substantive throughout the changeset.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/update-sshz-zig-0.16-EDHxe

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

@deepsource-io

deepsource-io Bot commented May 7, 2026 •

Copy link
Copy Markdown

DeepSource Code Review

We reviewed changes in af6f06a...b9ba2b5 on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Secrets May 7, 2026 1:17p.m. Review ↗

Important

AI Review is run only on demand for your team. We're only showing results of static analysis review right now. To trigger AI Review, comment @deepsourcebot review on this thread.

@codacy-production

codacy-production Bot commented May 7, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label May 7, 2026
Comment thread build.zig.zon
Comment on lines +9 to +10
.url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz",
.hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The dependency hash does not match the updated v0.1.5 tarball URL (it is still the old v0.1.2 hash), so Zig will reject this dependency during fetch/resolve and the project will fail to build. Regenerate and commit the correct hash for the v0.1.5 archive. [possible bug]

Severity Level: Critical 🚨
- ❌ `zig build` fails resolving zigzag v0.1.5 dependency.
- ❌ Main TUI binary using zigzag cannot be built.
- ⚠️ CI build pipeline fails at dependency resolution step.
Steps of Reproduction ✅
1. Install Zig 0.16.0 and clone the repository containing `build.zig` and `build.zig.zon`
(dependency config at `build.zig.zon:7-11` shows `zigzag` URL v0.1.5 with hash
`zigzag-0.1.2-...`).

2. From the repo root (`/workspace/sshz`), run `zig build` which loads `build.zig.zon` and
then executes `b.dependency("zigzag", .{ ... })` at `build.zig:7`.

3. The Zig package manager fetches
`https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz` using the hash from
`build.zig.zon:10` (`zigzag-0.1.2-YXwY...`).

4. Observe Zig abort the build with a dependency hash mismatch error (the stored v0.1.2
hash does not match the v0.1.5 tarball), so no build targets (including the main TUI in
`src/main.zig`) are produced.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** build.zig.zon
**Line:** 9:10
**Comment:**
	*Possible Bug: The dependency hash does not match the updated `v0.1.5` tarball URL (it is still the old `v0.1.2` hash), so Zig will reject this dependency during fetch/resolve and the project will fail to build. Regenerate and commit the correct hash for the `v0.1.5` archive.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

検証しました。この指摘は false positive です (4スレッド共通の返信)。

手元の Zig 0.16.0 で zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を実行した結果、得られたハッシュは現状の build.zig.zon の値と完全一致しました:

zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv

ハッシュの prefix zigzag-0.1.2- は 上流 zigzag の v0.1.5 タグ内 build.zig.zon の .version field がまだ "0.1.2" のまま であることに由来しており、Zig パッケージマネージャはこの内部 version を prefix に採用する仕様です (CodeRabbit のスクリプト調査結果と一致)。URL の v0.1.5 と内部 version 0.1.2 の不一致は上流側のメンテナンス問題であって、ハッシュ自体は正しい値です。

zig build および zig build test は Zig 0.16.0 で問題なく成功します。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Customized review instruction saved!

Instruction:

Do not flag Zig dependency hashes as incorrect solely because the hash prefix version differs from the tarball URL; verify the full hash value against zig fetch/build behavior before reporting a mismatch.

Applied to:

  • **/*.zon

💡 To manage or update this instruction, visit: CodeAnt AI Settings

Comment thread build.zig.zon
Comment on lines +9 to +10
.url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz",
.hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Architect Review — CRITICAL

The zigzag dependency URL was bumped to v0.1.5 while the hash still targets the v0.1.2 artifact, so Zig's package manager will reject the dependency and zig build will fail in normal workflows.

Suggestion: Regenerate and commit the correct hash for zigzag v0.1.5 using a Zig 0.16 toolchain (for example, zig fetch --save=zigzag <v0.1.5 url>) so the recorded hash matches the new URL.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is an **Architect / Logical Review** comment left during a code review. These reviews are first-class, important findings — not optional suggestions. Do NOT dismiss this as a 'big architectural change' just because the title says architect review; most of these can be resolved with a small, localized fix once the intent is understood.

**Path:** build.zig.zon
**Line:** 9:10
**Comment:**
	*CRITICAL: The zigzag dependency URL was bumped to v0.1.5 while the hash still targets the v0.1.2 artifact, so Zig's package manager will reject the dependency and `zig build` will fail in normal workflows.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
If a suggested approach is provided above, use it as the authoritative instruction. If no explicit code suggestion is given, you MUST still draft and apply your own minimal, localized fix — do not punt back with 'no suggestion provided, review manually'. Keep the change as small as possible: add a guard clause, gate on a loading state, reorder an await, wrap in a conditional, etc. Do not refactor surrounding code or expand scope beyond the finding.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

検証しました。この指摘は false positive です (4スレッド共通の返信)。

手元の Zig 0.16.0 で zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を実行した結果、得られたハッシュは現状の build.zig.zon の値と完全一致しました:

zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv

ハッシュの prefix zigzag-0.1.2- は 上流 zigzag の v0.1.5 タグ内 build.zig.zon の .version field がまだ "0.1.2" のまま であることに由来しており、Zig パッケージマネージャはこの内部 version を prefix に採用する仕様です (CodeRabbit のスクリプト調査結果と一致)。URL の v0.1.5 と内部 version 0.1.2 の不一致は上流側のメンテナンス問題であって、ハッシュ自体は正しい値です。

zig build および zig build test は Zig 0.16.0 で問題なく成功します。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Customized review instruction saved!

Instruction:

For Zig build.zig.zon dependency updates, do not flag a mismatch based only on the hash prefix version; verify the dependency with zig fetch/zig build first, since the recorded hash can still be correct even when the upstream tag and embedded package version differ.

Applied to:

  • **/build.zig.zon

💡 To manage or update this instruction, visit: CodeAnt AI Settings

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request updates the project to Zig 0.16.0 and migrates the codebase to a new I/O abstraction, passing std.Io and environment contexts through the application's core modules. Key changes include refactoring file I/O, networking, and process spawning to use the new std.Io interface, alongside updating the zigzag dependency. Feedback highlights a critical hash mismatch for the zigzag dependency in build.zig.zon and several instances of improper error handling where filesystem errors are silently swallowed during directory creation and backup management.

Comment thread build.zig.zon
.url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.2.tar.gz",
.hash = "zigzag-0.1.0-YXwYS20gCwATYmA0IOAYQVHykNP--Dl7bKfp2UDE0K2I",
.url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz",
.hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

As noted in the pull request description, this hash corresponds to version v0.1.2 but the URL points to v0.1.5. This mismatch will cause the build to fail. Please update the hash to the correct value for v0.1.5.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

検証しました。この指摘は false positive です (4スレッド共通の返信)。

手元の Zig 0.16.0 で zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を実行した結果、得られたハッシュは現状の build.zig.zon の値と完全一致しました:

zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv

ハッシュの prefix zigzag-0.1.2- は 上流 zigzag の v0.1.5 タグ内 build.zig.zon の .version field がまだ "0.1.2" のまま であることに由来しており、Zig パッケージマネージャはこの内部 version を prefix に採用する仕様です (CodeRabbit のスクリプト調査結果と一致)。URL の v0.1.5 と内部 version 0.1.2 の不一致は上流側のメンテナンス問題であって、ハッシュ自体は正しい値です。

zig build および zig build test は Zig 0.16.0 で問題なく成功します。

Comment thread src/meta.zig Outdated

std.fs.cwd().makePath(dir_path) catch {};
const cwd = std.Io.Dir.cwd();
cwd.createDirPath(io, dir_path) catch {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Swallowing all errors from createDirPath can hide critical issues such as PermissionDenied. While it is common to ignore errors if the directory already exists, other failure modes should be handled or propagated to ensure the application behaves predictably when the filesystem is not writable.

    cwd.createDirPath(io, dir_path) catch |err| if (err != error.PathAlreadyExists) return err;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。try cwd.createDirPath(io, dir_path) に変更しました。createDirPath は仕様上、既存ディレクトリでは成功を返す(PathAlreadyExists を返さない)ため、ガード分岐なしで素直に try で propagate しています。

Comment thread src/ssh_config.zig Outdated
std.fs.cwd().makePath(backup_dir) catch {};
fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, backup_dir: []const u8) !void {
const cwd = std.Io.Dir.cwd();
cwd.createDirPath(io, backup_dir) catch {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Ignoring all errors during directory creation for backups can lead to silent failures where no backups are actually created. It is recommended to handle or propagate errors other than PathAlreadyExists.

    cwd.createDirPath(io, backup_dir) catch |err| if (err != error.PathAlreadyExists) return err;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。backupFile の createDirPath を try に変更しました。同上の理由で PathAlreadyExists ガードは省略しています。

Comment thread src/ssh_config.zig Outdated
Comment on lines +338 to +343
const dest = cwd.createFile(io, backup_path, .{}) catch return;
defer dest.close(io);
var write_buf: [4096]u8 = undefined;
var w = dest.writer(io, &write_buf);
w.interface.writeAll(content) catch return;
w.interface.flush() catch return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using catch return in a function that returns !void will cause the function to return successfully (returning void) even if an I/O error occurs. This silences the error. It is more idiomatic to use try to propagate the error, especially since the caller already handles the error as a best-effort operation with catch {}.

        const dest = try cwd.createFile(io, backup_path, .{});
        defer dest.close(io);
        var write_buf: [4096]u8 = undefined;
        var w = dest.writer(io, &write_buf);
        try w.interface.writeAll(content);
        try w.interface.flush();

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。createFile/writeAll/flush を try に変更し、!void でのエラー伝搬に揃えました。呼び出し側 (writeFile) で backupFile(...) catch {} がベストエフォート扱いするのは従来通りです。

Comment thread src/ssh_config.zig Outdated
const to_delete = entries.items.len - 10;
for (entries.items[0..to_delete]) |name| {
dir.deleteFile(name) catch {};
dir.deleteFile(io, name) catch {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Swallowing errors during file deletion in rotateBackups can lead to an unbounded number of backup files if deletions fail silently (e.g., due to permissions). Since the function returns an error union, it is better to propagate the error or handle it explicitly.

        try dir.deleteFile(io, name);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。try dir.deleteFile(io, name) に変更しました。

Comment thread src/checker.zig
Comment on lines +84 to +86
self.threads_mutex.lockUncancelable(self.io);
const threads = self.threads.toOwnedSlice(self.allocator) catch return;
self.threads_mutex.unlock();
self.threads_mutex.unlock(self.io);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: joinAllThreads acquires threads_mutex and then returns immediately on allocation failure from toOwnedSlice without releasing the mutex. This leaves the mutex permanently locked, so later calls that need the same mutex can block forever. Ensure the mutex is always released on every exit path (including error paths). [possible bug]

Severity Level: Critical 🚨
- ❌ TUI status refresh can deadlock on low-memory allocation failure.
- ❌ `StatusChecker.deinit` may hang, blocking clean TUI shutdown.
- ⚠️ Background status-check worker threads may remain unjoined on error.
Steps of Reproduction ✅
1. Start the TUI via `main` at `src/main.zig:8-36` (which calls `launchTui` at
`src/main.zig:56-77` and constructs `app.Model` through `zz.Program(app.Model).init`).

2. In `Model.init` at `src/app.zig:61-89`, SSH host configuration is loaded and
`startStatusChecks()` is called at `src/app.zig:86`, which builds `CheckRequest` values
and calls `self.status_checker.checkAll(requests.items)` at `src/app.zig:130-131`.

3. Inside `StatusChecker.checkAll` at `src/checker.zig:92-111`, the first operation is
`self.joinAllThreads();` at `src/checker.zig:98`, which calls `joinAllThreads` at
`src/checker.zig:83-89`. There, `threads_mutex` is locked at line 84, and
`self.threads.toOwnedSlice(self.allocator)` at line 85 may fail under memory pressure (it
allocates a copy of the internal `threads` array using the same allocator used throughout
the TUI).

4. When `toOwnedSlice` fails, the `catch return` at `src/checker.zig:85` exits
`joinAllThreads` without executing the unlock at line 86, leaving `threads_mutex`
permanently locked. On the next status refresh (e.g., user presses 'r' in the TUI, which
calls `startStatusChecks` at `src/app.zig:115-133`, leading again to
`status_checker.checkAll` and `joinAllThreads`), or during shutdown via
`self.status_checker.deinit()` at `src/app.zig:92-100`,
`threads_mutex.lockUncancelable(self.io)` at `src/checker.zig:84` blocks forever,
deadlocking the status-checking logic and freezing that part of the TUI.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/checker.zig
**Line:** 84:86
**Comment:**
	*Possible Bug: `joinAllThreads` acquires `threads_mutex` and then returns immediately on allocation failure from `toOwnedSlice` without releasing the mutex. This leaves the mutex permanently locked, so later calls that need the same mutex can block forever. Ensure the mutex is always released on every exit path (including error paths).

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。toOwnedSlice の OOM 経路で unlock してから return するよう修正しました:

const threads = self.threads.toOwnedSlice(self.allocator) catch {
    self.threads_mutex.unlock(self.io);
    return;
};

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e1da21d6af

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/checker.zig
const stream = std.net.tcpConnectToHost(std.heap.page_allocator, hostname, port) catch return .offline;
stream.close();
fn tcpCheck(io: std.Io, hostname: []const u8, port: u16) HostStatus {
const host = std.Io.net.HostName.init(hostname) catch return .offline;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle IPv6 literals before HostName.init

For SSH configs whose effective HostName is an IPv6 literal such as ::1 or 2001:db8::1, this now returns .offline before any connection attempt because std.Io.net.HostName.init validates DNS host-name characters and rejects :. The previous std.net.tcpConnectToHost path accepted IP literals, so IPv6-only hosts will always show as offline in the status checker even when reachable; parse/connect std.Io.net.IpAddress literals first, or use an API path that accepts both IP literals and names.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。std.Io.net.IpAddress.parse を先に試して、IP リテラル (IPv4/IPv6) は HostName.init をバイパスして直接 addr.connect(io, ...) する経路を追加しました。これで ::1 や 2001:db8::1 のようなホスト名でもステータスチェックが通るようになります。

Comment thread src/app.zig Outdated
Comment on lines +406 to +407
self.meta_store.recordConnection(self.pa, self.io, entry.config.name) catch {};
meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: Connection metadata is recorded here and then recorded again in the direct-connect path after the TUI exits, so one user connection increments the counter twice and skews recency/order data. Remove one of the two recording points (typically keep it only in the final connect execution path) to avoid double-counting. [logic error]

Severity Level: Major ⚠️
- ⚠️ TUI-initiated connections double-increment `HostMeta.connect_count`.
- ⚠️ Future frequency-based features will see inflated connection counts.
- ⚠️ Extra redundant metadata write on every TUI connection.
Steps of Reproduction ✅
1. Launch the TUI by running `sshz` with no arguments, which enters `main.main` in
`src/main.zig:8-36` and then calls `launchTui(init)` at `src/main.zig:35-36`.

2. Inside `launchTui`, a `zz.Program(app.Model)` is created and run
(`src/main.zig:56-59`), which internally uses `app.Model.init` (`src/app.zig:61-89`) to
load config and metadata into `self.config` and `self.meta_store`.

3. In the TUI host list, select a host and press Enter; this drives `app.Model.update`
(`src/app.zig:152-176`) into the `.enter` branch in `handleKey` (`src/app.zig:290-295`),
which calls `self.connectToSelected()` at `src/app.zig:291-293`. `connectToSelected` at
`src/app.zig:403-409` immediately calls `self.meta_store.recordConnection(self.pa,
self.io, entry.config.name)` and `meta_mod.writeFile(self.pa, self.io, &self.meta_store,
self.meta_path)` (the snippet in question), incrementing `HostMeta.connect_count` and
updating `last_connected` in-memory and on disk.

4. After `program.run()` returns, `launchTui` copies `program.model.connect_host`
(`src/main.zig:61-67`), deinitializes the TUI (`src/main.zig:71-72`), and, if a host was
selected, calls `directConnect(allocator, init.io, init.environ_map, host_name, &.{})` at
`src/main.zig:74-76`. `directConnect` at `src/main.zig:79-88` reads the same meta store,
calls `store.recordConnection(allocator, io, host_name)` (`src/main.zig:87`, implemented
in `src/meta.zig:48-60`), and writes `meta.json` again. As a result, a single
TUI-initiated connection increments `HostMeta.connect_count` twice and bumps
`last_connected` twice for the same action.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/app.zig
**Line:** 406:407
**Comment:**
	*Logic Error: Connection metadata is recorded here and then recorded again in the direct-connect path after the TUI exits, so one user connection increments the counter twice and skews recency/order data. Remove one of the two recording points (typically keep it only in the final connect execution path) to avoid double-counting.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ご指摘内容は正しいですが、これは 本 PR で導入されたバグではなく master 時点から存在する既存バグ です (git diff master..HEAD -- src/app.zig で確認、connectToSelected の変更は IO 引数の追加のみ)。本 PR は Zig 0.16 への migration がスコープなので、ロジックの重複呼び出しの整理は別 PR で対応するのが適切と判断しました。修正案 (TUI 側の recordConnection を削除し directConnect 側に集約) は別 issue として追跡します。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Customized review instruction saved!

Instruction:

For one-time migration PRs, avoid flagging unrelated pre-existing logic issues; keep reviews focused on migration-only changes unless the PR itself introduces the bug.

Applied to:

  • **/migration*/**
  • **/*migration*.zig

💡 To manage or update this instruction, visit: CodeAnt AI Settings

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 316e53b。connectToSelected 側の recordConnection + writeFile を削除し、directConnect (TUI 終了後に呼ばれる) のみが記録するようにしました。これで TUI 経由の接続でも connect_count が二重インクリメントされなくなります。

別 PR で対応する旨の前回コメントを撤回し、本 PR で取り込みました (ユーザーリクエスト)。

Comment thread src/main.zig Outdated
}

// sshz <host> [command...] — direct connect
if (args.len >= 2 and args[1][0] != '-') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: This condition indexes the first byte of the second argument without checking that the argument string is non-empty. Running with an empty positional argument (for example sshz "") will trigger an out-of-bounds access. Check args[1].len > 0 before reading args[1][0]. [possible bug]

Severity Level: Major ⚠️
- ❌ CLI crashes on `sshz ""` or empty host argument.
- ⚠️ Scripts using empty-expanded host variables become fragile.
Steps of Reproduction ✅
1. Invoke the binary with an empty second argument, e.g. `sshz ""`, so the process
arguments array contains `argv[0] = "sshz"`, `argv[1] = ""`. `main.main` at
`src/main.zig:8-36` obtains `args` from `init.minimal.args.toSlice(arena_allocator)` at
`src/main.zig:12`.

2. With two arguments present, `args.len` is `2`, so the condition `if (args.len >= 2 and
args[1][0] != '-') {` at `src/main.zig:29-31` is evaluated. Because the `and` operator
evaluates the right-hand side when the left-hand side is true, `args[1][0]` is accessed
even though `args[1].len` is `0` for the empty string argument.

3. Indexing `args[1][0]` on a zero-length `[:0]const u8` slice is out-of-bounds in Zig,
and in safety-checked builds this triggers a runtime bounds check failure at
`src/main.zig:29`, causing the process to abort before any help text, error message, or
connection logic runs.

4. The direct-connect logic in `directConnect` (`src/main.zig:79-110`) is never reached,
so instead of treating an empty host as an invalid input or falling back to help, the CLI
simply crashes on this specific but realistic input pattern (for example, running `sshz
"$HOST"` when `$HOST` is unset).

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main.zig
**Line:** 29:29
**Comment:**
	*Possible Bug: This condition indexes the first byte of the second argument without checking that the argument string is non-empty. Running with an empty positional argument (for example `sshz ""`) will trigger an out-of-bounds access. Check `args[1].len > 0` before reading `args[1][0]`.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。args[1].len > 0 のガードを追加しました。

Comment thread src/ssh_config.zig
Comment on lines +308 to +309
var dir_fd = try cwd.openDir(io, dir_path, .{});
defer dir_fd.close(io);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The writer opens the parent directory directly but never ensures it exists, so saving fails with FileNotFound on environments where the config directory is absent (fresh machines/custom paths). Create the parent directory before openDir so writes are reliable. [possible bug]

Severity Level: Critical 🚨
- ❌ First-time host saves fail when `~/.ssh` directory is absent.
- ⚠️ UI reports "Host saved!" but no config file is written.
- ⚠️ New users can repeatedly lose hosts between TUI sessions.
Steps of Reproduction ✅
1. Run `sshz` on a user account that has no `~/.ssh` directory and no existing SSH config
file. `main.main` at `src/main.zig:8-36` launches the TUI with `launchTui(init)` at
`src/main.zig:35-36`, which constructs `zz.Program(app.Model)` (`src/main.zig:56-59`).
`app.Model.init` (`src/app.zig:61-89`) computes `self.config_path` via
`ssh_config.defaultConfigPath(self.pa, self.env)` (`src/ssh_config.zig:381-383`), yielding
a path like `$HOME/.ssh/config`. The subsequent call `ssh_config.readFile(self.pa,
self.io, self.config_path)` at `src/app.zig:75` fails with `error.FileNotFound`, which is
caught and replaced with an empty `ssh_config.Config` (`src/app.zig:75-78`), so the TUI
loads with an empty host list.

2. Inside the TUI, add a host via the add form. This goes through `handleKey` into
`handleFormKey` (`src/app.zig:303-327`), which on Enter calls `self.saveForm()` at
`src/app.zig:311-313`. `saveForm` builds a `ssh_config.Host` and appends it to
`self.config`, then invokes `ssh_config.writeFile(self.pa, self.io, &self.config,
self.config_path, self.backup_dir)` at `src/app.zig:457-458`, where `self.config_path`
still points to `$HOME/.ssh/config`.

3. `ssh_config.writeFile` at `src/ssh_config.zig:295-320` first calls `backupFile`
(`src/ssh_config.zig:323-347`), which ensures the backup directory `self.backup_dir`
exists, but it never creates the parent directory for `self.config_path`. After
serialization, it sets `dir_path = std.fs.path.dirname(path) orelse "."` and `basename =
std.fs.path.basename(path)` at `src/ssh_config.zig:301-302`, then does `const cwd =
std.Io.Dir.cwd(); var dir_fd = try cwd.openDir(io, dir_path, .{});` at
`src/ssh_config.zig:307-309`. When `dir_path` is `$HOME/.ssh` and that directory does not
yet exist, `cwd.openDir` fails with `error.FileNotFound`, causing `writeFile` to return an
error.

4. Back in `saveForm`, the `writeFile` error is ignored via `catch {}`
(`src/app.zig:457-458`), and the function continues to rebuild the host list and set
`self.notification = "Host saved!"` at `src/app.zig:473-476`. The user sees "Host saved!"
but no `~/.ssh/config` file is actually created. On the next run, `app.Model.init` again
catches `error.FileNotFound` and loads an empty config, so the host silently disappears,
demonstrating that missing parent directories for the config path cause persistent save
failures.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/ssh_config.zig
**Line:** 308:309
**Comment:**
	*Possible Bug: The writer opens the parent directory directly but never ensures it exists, so saving fails with `FileNotFound` on environments where the config directory is absent (fresh machines/custom paths). Create the parent directory before `openDir` so writes are reliable.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 3f625e2。writeFile で openDir の前に try cwd.createDirPath(io, dir_path) を呼ぶよう修正しました (meta.zig の writeFile と同じパターン)。

@codeant-ai

codeant-ai Bot commented May 7, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
src/ssh_config.zig (1)

301-320: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

~/.ssh がまだ無い環境だと初回保存に失敗します。

ここは dir_path を作成せずに openDir しているので、初回利用時に ~/.ssh が存在しないと書き込めません。openDir の前で createDirPath(io, dir_path) を呼んでください。

修正例
     const dir_path = std.fs.path.dirname(path) orelse ".";
     const basename = std.fs.path.basename(path);
 
     var tmp_name_buf: [256]u8 = undefined;
     const tmp_name = std.fmt.bufPrint(&tmp_name_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong;
 
     const cwd = std.Io.Dir.cwd();
+    try cwd.createDirPath(io, dir_path);
     var dir_fd = try cwd.openDir(io, dir_path, .{});
     defer dir_fd.close(io);
🤖 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 `@src/ssh_config.zig` around lines 301 - 320, The code attempts to open
dir_path with cwd.openDir without ensuring the directory exists, causing
failures when ~/.ssh is missing; before calling cwd.openDir(io, dir_path) (where
dir_path is computed from std.fs.path.dirname(path)), call createDirPath(io,
dir_path) to create the directory hierarchy, then proceed to openDir and the tmp
file write/rename flow (ensure any errors from createDirPath are propagated).
src/app.zig (2)

479-496: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

ソート/フィルタ中に別のホストを削除してしまいます。

self.selected は表示中の一覧インデックスですが、ここでは self.config.hosts の素の順序で config_index を引き直しています。並び替え後や検索/タグ絞り込み中だと、選択中ではないホストを消します。選択中の self.hosts.items[self.selected].config.name など、実際に表示しているエントリから削除対象を特定してください。

修正例
-        var config_index: ?usize = null;
-        var display_i: usize = 0;
-        for (self.config.hosts, 0..) |h, ci| {
-            if (h.is_wildcard) continue;
-            if (display_i == self.selected) {
-                config_index = ci;
-                break;
-            }
-            display_i += 1;
-        }
+        const selected_name = self.hosts.items[self.selected].config.name;
+        var config_index: ?usize = null;
+        for (self.config.hosts, 0..) |h, ci| {
+            if (std.mem.eql(u8, h.name, selected_name)) {
+                config_index = ci;
+                break;
+            }
+        }
🤖 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 `@src/app.zig` around lines 479 - 496, deleteSelectedHost currently recomputes
config_index by iterating raw self.config.hosts, which breaks when the UI list
is sorted/filtered; instead determine the actual entry to delete from the
visible list using self.hosts.items[self.selected].config.name (or another
unique field from the displayed item), find the matching host in
self.config.hosts by comparing that name (or id) to locate the correct ci, then
call ssh_config.removeHost(self.pa, &self.config, ci) and
ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path,
self.backup_dir) as before; update deleteSelectedHost to use the visible-item ->
match-in-config approach to compute ci rather than relying on display_i.

460-471: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

タグを空にしても既存タグが消えません。

tags_val.len == 0 のとき setTags を呼ばないので、編集画面でタグを全削除して保存しても古いタグが残ります。空配列でも保存するか、明示的な削除パスを用意してください。

修正例
-        if (tags_val.len > 0) {
-            var tags: std.ArrayList([]const u8) = .empty;
-            defer tags.deinit(self.pa);
-            var tag_it = std.mem.splitScalar(u8, tags_val, ',');
-            while (tag_it.next()) |tag| {
-                const trimmed = std.mem.trim(u8, tag, " ");
-                if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {};
-            }
-            self.meta_store.setTags(self.pa, name, tags.items) catch {};
-        }
+        var tags: std.ArrayList([]const u8) = .empty;
+        defer tags.deinit(self.pa);
+        var tag_it = std.mem.splitScalar(u8, tags_val, ',');
+        while (tag_it.next()) |tag| {
+            const trimmed = std.mem.trim(u8, tag, " ");
+            if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {};
+        }
+        self.meta_store.setTags(self.pa, name, tags.items) catch {};
🤖 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 `@src/app.zig` around lines 460 - 471, tags_val.len == 0 currently skips
calling self.meta_store.setTags so deleting all tags in the UI leaves older tags
intact; change the logic so that setTags is always called: if tags_val.len == 0
call self.meta_store.setTags(self.pa, name, &[_][]const u8{}) (or build an empty
std.ArrayList and pass its .items) to persist an empty tag list, otherwise
parse/trim and pass tags.items as before, and keep meta_mod.writeFile(self.pa,
self.io, &self.meta_store, self.meta_path) as-is.
src/meta.zig (1)

160-209: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

JSON を手組みしているので文字列内容で壊れます。

ホスト名、タグ、forward の各文字列をエスケープせずにそのまま埋め込んでいるため、" や \ を含む値で meta.json が不正になります。その後 Line 219 で空の MetaStore にフォールバックするので、履歴やタグが実質消えます。文字列を必ず JSON エスケープして出力してください。

🤖 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 `@src/meta.zig` around lines 160 - 209, The serialize function builds JSON by
concatenating raw strings (see serialize, buf.appendSlice usages) which breaks
when host names, tags, or port-forward fields contain quotes/backslashes;
replace direct appends of entry.key_ptr.*, tag, fwd.forward_type, fwd.bind, and
fwd.target with JSON-escaped versions. Implement or use a JSON-escape helper
(e.g., jsonEscape(allocator, []const u8) ![]const u8) that returns an escaped
slice and call that before appending (remember to free/defer the escaped slice),
then append the escaped slice instead of the raw value in all places where
buf.appendSlice currently takes unescaped strings. Ensure the helper handles
quotes, backslashes and control characters to produce valid JSON string content.
🤖 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 `@build.zig.zon`:
- Around line 9-10: build.zig.zon の .url が v0.1.5 を指している一方で .hash のプレフィックスは
zigzag-0.1.2- と内部バージョンが不一致なので、パッケージハッシュを再生成して一致させてください(対象: build.zig.zon の
.url/.hash、パッケージ名 zigzag)。具体的には上流 URL
https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を用いて zig
fetch --save=zigzag を実行して正しいハッシュを取得し、.hash を置き換えるか、あるいは upstream の build.zig.zon
の version フィールドを 0.1.5 に修正するよう報告してください。

In `@src/checker.zig`:
- Around line 83-89: joinAllThreads currently locks threads_mutex and then calls
self.threads.toOwnedSlice(self.allocator) but on OOM the catch returns without
unlocking the mutex, risking deadlock; fix by ensuring the mutex is released in
the error path (replace the `catch return` with `catch {
self.threads_mutex.unlock(self.io); return }`), so that joinAllThreads always
unlocks threads_mutex when toOwnedSlice fails before returning (keep the
existing explicit unlock before the join loop).

In `@src/main.zig`:
- Around line 29-30: 要約: args[1][0] を直接参照しているため空文字の引数で境界外アクセスが発生します。fix: main
の該当条件を修正して args[1] の長さを先にチェックし、args[1].len > 0 を追加してから args[1][0] != '-'
を評価するようにしてください(参照箇所: 条件式で args, args[1], args[1][0] を扱っているブロックと directConnect
呼び出し)。また、args[1] が空なら directConnect を呼ばないように分岐を整えてください。

In `@src/ssh_config.zig`:
- Around line 288-292: readFile currently frees the buffer `content` before
returning, but `parse` stores slices from `content` into Config.hosts and
Config.raw_lines, creating dangling references; fix by making Config own the
original buffer (e.g. add a field like raw_buffer: []u8 and assign `raw_buffer =
content` in parse/readFile and remove the `defer allocator.free(content)`), or
alternatively modify `parse` to deep-copy all strings into allocator-allocated
buffers (use allocator to alloc/copy for entries stored in Config.hosts and
Config.raw_lines) so the returned Config does not reference freed memory; update
readFile and parse accordingly (referencing readFile, parse, Config.hosts,
Config.raw_lines, content, allocator.free).

---

Outside diff comments:
In `@src/app.zig`:
- Around line 479-496: deleteSelectedHost currently recomputes config_index by
iterating raw self.config.hosts, which breaks when the UI list is
sorted/filtered; instead determine the actual entry to delete from the visible
list using self.hosts.items[self.selected].config.name (or another unique field
from the displayed item), find the matching host in self.config.hosts by
comparing that name (or id) to locate the correct ci, then call
ssh_config.removeHost(self.pa, &self.config, ci) and
ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path,
self.backup_dir) as before; update deleteSelectedHost to use the visible-item ->
match-in-config approach to compute ci rather than relying on display_i.
- Around line 460-471: tags_val.len == 0 currently skips calling
self.meta_store.setTags so deleting all tags in the UI leaves older tags intact;
change the logic so that setTags is always called: if tags_val.len == 0 call
self.meta_store.setTags(self.pa, name, &[_][]const u8{}) (or build an empty
std.ArrayList and pass its .items) to persist an empty tag list, otherwise
parse/trim and pass tags.items as before, and keep meta_mod.writeFile(self.pa,
self.io, &self.meta_store, self.meta_path) as-is.

In `@src/meta.zig`:
- Around line 160-209: The serialize function builds JSON by concatenating raw
strings (see serialize, buf.appendSlice usages) which breaks when host names,
tags, or port-forward fields contain quotes/backslashes; replace direct appends
of entry.key_ptr.*, tag, fwd.forward_type, fwd.bind, and fwd.target with
JSON-escaped versions. Implement or use a JSON-escape helper (e.g.,
jsonEscape(allocator, []const u8) ![]const u8) that returns an escaped slice and
call that before appending (remember to free/defer the escaped slice), then
append the escaped slice instead of the raw value in all places where
buf.appendSlice currently takes unescaped strings. Ensure the helper handles
quotes, backslashes and control characters to produce valid JSON string content.

In `@src/ssh_config.zig`:
- Around line 301-320: The code attempts to open dir_path with cwd.openDir
without ensuring the directory exists, causing failures when ~/.ssh is missing;
before calling cwd.openDir(io, dir_path) (where dir_path is computed from
std.fs.path.dirname(path)), call createDirPath(io, dir_path) to create the
directory hierarchy, then proceed to openDir and the tmp file write/rename flow
(ensure any errors from createDirPath are propagated).
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3286812e-c36e-4381-bffa-5cb9257ca6c3

📥 Commits

Reviewing files that changed from the base of the PR and between af6f06a and e1da21d.

📒 Files selected for processing (14)
  • .github/workflows/ci.yml
  • .gitignore
  • build.zig.zon
  • src/app.zig
  • src/checker.zig
  • src/main.zig
  • src/meta.zig
  • src/ssh_config.zig
  • src/utils.zig
  • src/views/forward.zig
  • src/views/help.zig
  • src/views/host_form.zig
  • src/views/host_list.zig
  • tests/test_meta.zig

Comment thread build.zig.zon
Comment on lines +9 to +10
.url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz",
.hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv",

@coderabbitai coderabbitai Bot May 7, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# zigzag v0.1.5 アーカイブ内の build.zig.zon の .version フィールドを確認する
# 期待値: "0.1.5" (正しく更新されていれば) / "0.1.2" (内部バージョンが古いまま)
curl -sL "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz" \
  | tar -xzO --wildcards '*/build.zig.zon' 2>/dev/null | grep -E '\.version'

Repository: midasdf/sshz

Length of output: 1943


🏁 Script executed:

#!/bin/bash
# Download and check the build.zig.zon version in zigzag v0.1.5
curl -sL "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz" \
  | tar -xzO --wildcards '*/build.zig.zon' 2>/dev/null | grep -E '\.version|\.name'

Repository: midasdf/sshz

Length of output: 101


URL の v0.1.5 とハッシュが示す内部バージョン 0.1.2 が一致していない

上流パッケージの v0.1.5 タグの build.zig.zon に記載されているバージョンが実際に 0.1.2 であることが確認されました。Zig パッケージマネージャのハッシュプレフィックス(zigzag-0.1.2-)はこの内部バージョンから生成されるため、ハッシュ自体は正しいですが、URL のタグ(v0.1.5)と内部バージョン(0.1.2)のズレが示す通り、上流パッケージのメンテナンスに問題があります。

以下を実行してハッシュを再生成してください:

zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz

または上流プロジェクト(meszmate/zigzag)に対して、v0.1.5 タグの build.zig.zon のバージョン文字列を 0.1.5 に更新するよう報告することを推奨します。

🤖 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 `@build.zig.zon` around lines 9 - 10, build.zig.zon の .url が v0.1.5 を指している一方で
.hash のプレフィックスは zigzag-0.1.2- と内部バージョンが不一致なので、パッケージハッシュを再生成して一致させてください(対象:
build.zig.zon の .url/.hash、パッケージ名 zigzag)。具体的には上流 URL
https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を用いて zig
fetch --save=zigzag を実行して正しいハッシュを取得し、.hash を置き換えるか、あるいは upstream の build.zig.zon
の version フィールドを 0.1.5 に修正するよう報告してください。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

検証しました。この指摘は false positive です (4スレッド共通の返信)。

手元の Zig 0.16.0 で zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を実行した結果、得られたハッシュは現状の build.zig.zon の値と完全一致しました:

zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv

ハッシュの prefix zigzag-0.1.2- は 上流 zigzag の v0.1.5 タグ内 build.zig.zon の .version field がまだ "0.1.2" のまま であることに由来しており、Zig パッケージマネージャはこの内部 version を prefix に採用する仕様です (CodeRabbit のスクリプト調査結果と一致)。URL の v0.1.5 と内部 version 0.1.2 の不一致は上流側のメンテナンス問題であって、ハッシュ自体は正しい値です。

zig build および zig build test は Zig 0.16.0 で問題なく成功します。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@midasdf、ご確認とご説明ありがとうございます。おっしゃる通り、この指摘は false positive でした。

Zig パッケージマネージャのハッシュプレフィックスは git タグ ではなく、依存パッケージ自身の build.zig.zon 内 .version フィールド から生成される仕様であることを見落としていました。上流の meszmate/zigzag の v0.1.5 タグ内 .version が "0.1.2" のままであるため、zig fetch が出力するハッシュのプレフィックスが zigzag-0.1.2- となるのは正しい挙動です。

現状の build.zig.zon のハッシュ値は正確であり、問題ありません。失礼しました。


✏️ Learnings added
Learnt from: midasdf
Repo: midasdf/sshz PR: 3
File: build.zig.zon:9-10
Timestamp: 2026-05-07T12:39:04.143Z
Learning: In Zig's package manager (build.zig.zon), the hash prefix for a dependency (e.g., `zigzag-0.1.2-...`) is derived from the `.version` field inside the **dependency's own `build.zig.zon`**, not from the git tag used in the `.url`. Therefore, a mismatch between the URL's git tag version (e.g., `v0.1.5`) and the hash prefix version (e.g., `0.1.2`) is expected when the upstream package's internal version string has not been updated to match the tag. The hash is still valid and correct in such cases.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment thread src/checker.zig Resolved
Comment thread src/main.zig Resolved
Comment thread src/ssh_config.zig Resolved
- main: guard args[1][0] with len > 0 to avoid OOB on empty arg
- checker: unlock mutex on toOwnedSlice OOM in joinAllThreads
- checker: parse IPv4/IPv6 literals before HostName.init so bare
  IPv6 hosts no longer always report offline
- ssh_config: createDirPath before openDir in writeFile so save
  succeeds when ~/.ssh is missing
- ssh_config/meta: propagate dir/file errors instead of swallowing
  them in createDirPath/backupFile/rotateBackups
@midasdf

midasdf commented May 7, 2026

Copy link
Copy Markdown
Owner Author

レビュー対応サマリ (commit 3f625e2)

✅ Fixed (migration scope)

# File Issue 反映
1 src/main.zig:29 空文字引数 (sshz "") で args[1][0] OOB args[1].len > 0 ガード追加
2 src/checker.zig:85 joinAllThreads で toOwnedSlice OOM 時 mutex 未解放 → デッドロック catch 経路で unlock してから return
3 src/checker.zig:157 HostName.init が : を拒否、IPv6 リテラルが常に offline 判定 IpAddress.parse を先に試す経路を追加
4 src/ssh_config.zig:308 ~/.ssh 不在時 openDir が FileNotFound で save失敗 try cwd.createDirPath を openDir 前に呼ぶ
5 src/ssh_config.zig:325 backupFile の createDirPath がエラーを呑む try cwd.createDirPath
6 src/ssh_config.zig:343 backupFile の createFile/writeAll/flush で catch return (エラー silenced) try で伝搬
7 src/ssh_config.zig:377 rotateBackups の deleteFile がエラーを呑む try dir.deleteFile
8 src/meta.zig:230 writeFile の createDirPath がエラーを呑む try cwd.createDirPath

zig build / zig build test / --help / --version smoke test、いずれも Zig 0.16.0 で通過確認済み。

❌ False positive — push back

build.zig.zon のハッシュ不整合 (CodeAnt × 2 / Gemini / CodeRabbit の計4スレッド): 手元の Zig 0.16.0 で zig fetch --save=zigzag https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz を実行した結果、得られるハッシュは現状の build.zig.zon の値と完全一致 (zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv)。プレフィックス zigzag-0.1.2- は 上流 zigzag の v0.1.5 タグ内 build.zig.zon の .version field がまだ "0.1.2" のままである ことに由来する正常仕様 (CodeRabbit のスクリプト調査結果と一致)。zig build 成功。

⏭ Out of scope — pre-existing bugs (別 PR/issue で対応)

git diff master..HEAD で確認した結果、以下は 本 PR で導入されたバグではなく master 時点から存在 する既存バグです。本 PR は Zig 0.16 migration がスコープのため別途対応します:

  • src/ssh_config.zig parse() の dangling buffer (Config.hosts/raw_lines が解放済み content のスライスを保持) — CodeRabbit Critical
  • src/meta.zig serialize() の JSON 文字列エスケープ抜け ("/\\ で破損) — CodeRabbit Major
  • src/app.zig deleteSelectedHost() がソート/フィルタ中に間違うホストを削除 (display index と config index の不一致) — CodeRabbit Critical
  • src/app.zig saveForm() で tags_val.len == 0 時に setTags をスキップ → 空タグ保存不可 — CodeRabbit Major
  • src/app.zig connectToSelected() の recordConnection が TUI 終了後の directConnect でも再度呼ばれて double-count — CodeAnt Major

それぞれの修正案は各レビューコメントに記載されている通りで、別 PR で個別対応します。

@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

🧹 Nitpick comments (1)
src/meta.zig (1)

212-219: 💤 Low value

readFileAlloc のシグネチャは Zig 0.16 に準拠している。

readFileAlloc の新しいシグネチャは readFileAlloc(file_name, allocator, .limited(N)) ですが、 std.Io.Dir 経由では readFileAlloc(io, path, arena, .limited(1000)) の形が正しく、 Line 214 のコードはこれに合致しています。

ただし Line 219 で parse 失敗を無条件に MetaStore.initWith(allocator) に fallback している点は、破損したメタデータファイルを無音で上書きするリスクがあります。既存の挙動の踏襲であれば許容範囲ですが、警告ログの追加を検討してください。

🤖 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 `@src/meta.zig` around lines 212 - 219, The readFile function currently
swallows parse errors and unconditionally returns MetaStore.initWith(allocator),
which can silently overwrite a corrupted metadata file; change the error path
after parse(allocator, content) to log a warning including the parse error and
the path (use std.debug.warn or the existing logging facility) before returning
MetaStore.initWith(allocator), and ensure the message references the failed
parse error and the path variable so callers/ops can detect corrupt metadata;
update the readFile code around the parse call and the return to emit that
warning when parse fails.
🤖 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 `@src/meta.zig`:
- Around line 48-49: The call to std.Io.Timestamp.now(...) is using the wrong
Zig 0.16 API and will not compile; in recordConnection (MetaStore) replace the
incorrect timestamp invocation used to set the local variable now with the Zig
0.16 pattern: call std.Io.Clock.real.now(io) and then call .toSeconds() on its
result so now becomes the seconds value; update any imports/usages in
recordConnection that assume std.Io.Timestamp accordingly.
- Line 247: The call to dir_fd.rename has the arguments in the wrong order and
must follow the std.Io.Dir API convention of taking io as the first parameter;
update the call using the dir_fd.rename invocation so that io is passed first
followed by tmp_name, the target dir handle (dir_fd), and basename (i.e.,
reorder the parameters accordingly), and make the same fix for the analogous
call in src/ssh_config.zig where dir_fd.rename is used.

---

Nitpick comments:
In `@src/meta.zig`:
- Around line 212-219: The readFile function currently swallows parse errors and
unconditionally returns MetaStore.initWith(allocator), which can silently
overwrite a corrupted metadata file; change the error path after
parse(allocator, content) to log a warning including the parse error and the
path (use std.debug.warn or the existing logging facility) before returning
MetaStore.initWith(allocator), and ensure the message references the failed
parse error and the path variable so callers/ops can detect corrupt metadata;
update the readFile code around the parse call and the return to emit that
warning when parse fails.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3572d26b-fb77-48d0-811b-752b22b11aeb

📥 Commits

Reviewing files that changed from the base of the PR and between e1da21d and 3f625e2.

📒 Files selected for processing (4)
  • src/checker.zig
  • src/main.zig
  • src/meta.zig
  • src/ssh_config.zig
✅ Files skipped from review due to trivial changes (2)
  • src/main.zig
  • src/ssh_config.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/checker.zig

Comment thread src/meta.zig
Comment on lines +48 to +49
pub fn recordConnection(self: *MetaStore, allocator: std.mem.Allocator, io: std.Io, name: []const u8) !void {
const now = std.Io.Timestamp.now(io, .real).toSeconds();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

Zig 0.16 std.Io.Timestamp.now real clock toSeconds API

💡 Result:

In Zig 0.16 (std.Io), to get the real (wall-clock-like) timestamp and convert it to seconds, use std.Io.Clock.real.now(io) and then call.toSeconds on the returned Timestamp. Example: const std = @import("std"); const Io = std.Io; pub fn main!void { var threaded: Io.Threaded =.init_single_threaded; defer threaded.deinit; const io = threaded.io; const ts = try Io.Clock.real.now(io); // returns a std.Io.Timestamp const seconds: i64 = ts.toSeconds; _ = seconds; } Notes grounded in sources: - std.Io.Clock.real.now(io) returns a std.Io.Timestamp, and Timestamp provides toSeconds for conversion to integer seconds [1]. - Io.Clock.now / Timestamp unit assumptions can vary by platform/clock implementation (e.g., Windows QPC details), so prefer computing elapsed durations via durationTo / since rather than assuming nanoseconds always map 1:1 everywhere [2]. Top sources used: [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
# std.Io.Timestamp の定義と toSeconds/now メソッドを検索
rg -n "Timestamp" --type=zig -C 3

Repository: midasdf/sshz

Length of output: 1835


Zig 0.16 の std.Io.Timestamp API が正確でない可能性があります。

公式ドキュメントによると、Zig 0.16 で実時間タイムスタンプを取得するには std.Io.Clock.real.now(io) を使用して、その後に .toSeconds() を呼び出す必要があります。現在のコードで使用されている std.Io.Timestamp.now(io, .real) というパターンとは異なります。この API 呼び出しは、記述されたコードでコンパイルエラーになる可能性があります。

🤖 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 `@src/meta.zig` around lines 48 - 49, The call to std.Io.Timestamp.now(...) is
using the wrong Zig 0.16 API and will not compile; in recordConnection
(MetaStore) replace the incorrect timestamp invocation used to set the local
variable now with the Zig 0.16 pattern: call std.Io.Clock.real.now(io) and then
call .toSeconds() on its result so now becomes the seconds value; update any
imports/usages in recordConnection that assume std.Io.Timestamp accordingly.

Comment thread src/meta.zig
}

try dir_fd.rename(tmp_name, basename);
try dir_fd.rename(tmp_name, dir_fd, basename, io);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# std.Io.Dir.rename のシグネチャを検索
rg -n "fn rename" --type=zig -C 5

Repository: midasdf/sshz

Length of output: 38


🏁 Script executed:

cd /tmp && find . -name "src" -type d 2>/dev/null | head -5

Repository: midasdf/sshz

Length of output: 38


🏁 Script executed:

git ls-files | head -20

Repository: midasdf/sshz

Length of output: 409


🏁 Script executed:

cat -n src/meta.zig | sed -n '240,255p'

Repository: midasdf/sshz

Length of output: 791


🏁 Script executed:

rg "\.rename\(" -B 2 -A 2

Repository: midasdf/sshz

Length of output: 349


🏁 Script executed:

rg "rename" --type zig

Repository: midasdf/sshz

Length of output: 198


🏁 Script executed:

cat -n build.zig

Repository: midasdf/sshz

Length of output: 3806


🏁 Script executed:

cat -n src/meta.zig | sed -n '220,250p'

Repository: midasdf/sshz

Length of output: 1332


🏁 Script executed:

rg "\.createDirPath\(|\.openDir\(|\.writeFile\(|\.close\(" -B 1 -A 1 | head -40

Repository: midasdf/sshz

Length of output: 1727


🏁 Script executed:

rg "io" src/meta.zig | head -20

Repository: midasdf/sshz

Length of output: 1111


🏁 Script executed:

cat -n src/ssh_config.zig | sed -n '200,220p'

Repository: midasdf/sshz

Length of output: 948


🏁 Script executed:

rg "\.rename\(" -B 3 -A 3

Repository: midasdf/sshz

Length of output: 696


rename の引数順序が誤っており、コンパイルエラーになる。

ファイル内のすべての std.Io.Dir API 呼び出しは io を第1引数として受け取ります:

  • cwd.createDirPath(io, dir_path) (230行)
  • cwd.openDir(io, dir_path, .{}) (235行)
  • dir_fd.close(io) (236行)
  • dir_fd.createFile(io, tmp_name, .{}) (239行)
  • tmp_file.writer(io, &write_buf) (242行)

しかし247行の dir_fd.rename(tmp_name, dir_fd, basename, io) は io を末尾に配置しており、パターンに矛盾しています。同じ誤りは src/ssh_config.zig にも存在します。

修正案
-    try dir_fd.rename(tmp_name, dir_fd, basename, io);
+    try dir_fd.rename(io, tmp_name, dir_fd, basename);
📝 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
try dir_fd.rename(tmp_name, dir_fd, basename, io);
try dir_fd.rename(io, tmp_name, dir_fd, basename);
🤖 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 `@src/meta.zig` at line 247, The call to dir_fd.rename has the arguments in the
wrong order and must follow the std.Io.Dir API convention of taking io as the
first parameter; update the call using the dir_fd.rename invocation so that io
is passed first followed by tmp_name, the target dir handle (dir_fd), and
basename (i.e., reorder the parameters accordingly), and make the same fix for
the analogous call in src/ssh_config.zig where dir_fd.rename is used.

- ssh_config: Config now owns the raw file buffer so hosts/raw_lines
  slices remain valid after readFile (CodeRabbit critical: dangling
  reference on `parse` content)
- meta: JSON-escape host names, tags, and port-forward fields when
  serialising so values containing `"`, `\\`, or control characters
  no longer corrupt meta.json (CodeRabbit major)
- app.deleteSelectedHost: look up the config entry by name from the
  visible list instead of by display index, so sorting no longer
  causes the wrong host to be deleted (CodeRabbit critical)
- app.saveForm: always call setTags so clearing the tags field in
  the edit form persists an empty list (CodeRabbit major)
- app.connectToSelected: stop recording the connection in the TUI
  path; directConnect already records it after the TUI exits, so
  this was double-counting connect_count (CodeAnt major)
@midasdf

midasdf commented May 7, 2026

Copy link
Copy Markdown
Owner Author

追加対応 — pre-existing バグも修正 (commit 316e53b)

前のサマリで「別 PR で対応」とした 5 件、すべて本 PR に取り込みました (ユーザーリクエスト)。

修正内容

# File / Function 対応
1 src/ssh_config.zig parse() dangling buffer Config に raw_buffer: []u8 を追加。readFile で content の所有権を Config に移譲し、deinit で解放。デフォルト値 &[_]u8{} で空 Config フォールバック (app.zig:75) でも安全
2 src/meta.zig serialize() JSON エスケープ appendJsonString ヘルパーを追加し、ホスト名・タグ・port-forward の各文字列を "/\\/制御文字 (\b\f\n\r\t\u00xx) でエスケープして出力
3 src/app.zig deleteSelectedHost() filter/sort display index ベースの探索を、可視リスト (self.hosts.items[self.selected].config.name) からの 名前ベース lookup に変更
4 src/app.zig saveForm() tags 空ケース tags_val.len > 0 ガードを除去し、常に setTags(name, parsed_tags.items) を呼ぶように変更。空入力時は空配列を保存
5 src/app.zig connectToSelected() double-record TUI 側の recordConnection + writeFile を削除。directConnect が TUI 終了後に必ず record するので、これで TUI 経由接続の二重カウントが解消

zig build / zig build test (既存の serialize/parse round-trip 含む) いずれも通過。

注意事項

  • app.zig の filter/sort 周りには別の architectural issue が残ります: selected インデックスは model.hosts.items ベースで管理される一方、レンダラ (views/host_list.zig) は search/tag フィルタ後の display_idx で選択判定するため、フィルタ適用中は selected と表示位置がズレます。moveUp/moveDown もフィルタを意識していません。今回の修正で sort 由来の delete 誤爆は塞いだ前提で、フィルタ整合性の改修は別 PR/issue で対応するのが筋と考えます。
  • ssh_config の addHost で allocPrint した行文字列が deinit で個別解放されない既存の leak は残っていますが、これは本レビュー指摘の範囲外なのでスコープアウト。

各 inline スレッド (#3199706426, #3199746314) にも対応コメントを追記済みです。

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 316e53be83

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/checker.zig
return .online;
} else |_| {}

const host = std.Io.net.HostName.init(hostname) catch return .offline;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Accept resolver names that are not DNS labels

For SSH configs whose effective host name is a resolver/hosts-file name that is valid for ssh but not a strict DNS label, such as db_test, this returns .offline without attempting a lookup because std.Io.net.HostName.init only permits ASCII alphanumerics, -, and .. The old std.net.tcpConnectToHost path delegated these names to the system resolver, so hosts that connect successfully via /etc/hosts or local resolver aliases are now always shown offline; use a lookup/connect path that accepts the same name syntax SSH can resolve, or only apply HostName.init after handling these cases.

Useful? React with 👍 / 👎.

midasdf added 2 commits May 7, 2026 22:12
…sync

Move filter logic from the renderer into Model.rebuildVisibleIndices.
`selected` is now an index into `visible_indices` (the filtered display
order), so navigation, edit ('e'), forward ('f'), delete ('d'),
connect (Enter), and confirm-delete prompts all reference the same
host the user actually sees highlighted, regardless of search text or
tag filter.

- add Model.visible_indices, rebuilt on rebuildHostList,
  cycleSortMode, cycleTagFilter, and every search-text mutation
- moveDown bounds-check against visible_indices.items.len
- views/host_list.zig drops matchesSearch/hasTag (now in app.zig)
  and iterates model.visible_indices directly
`parse` previously returned a `Config` whose `Host` fields and
`raw_lines` borrowed from the input buffer; `addHost` mixed in
allocPrint'd lines, leaving `deinit` unable to tell which strings to
free. The pre-existing leak forced one test to use `page_allocator`
and skip `deinit` entirely.

This change makes Config the sole owner of every string inside it:

- `parse` deep-copies host names, host fields, and every raw line
  (with `errdefer` cleanup on partial OOM)
- `setHostField` becomes fallible and dupes its value
- `addHost` deep-copies its incoming `Host` and lines, then commits
  with a two-phase swap so a failed `toOwnedSlice` doesn't strand
  half-owned state on `config`
- `removeHost` frees the dropped host's strings and the dropped
  `raw_lines` entries
- `Config.deinit` walks hosts/lines and frees their strings via a
  shared `freeHostStrings` helper
- `readFile` reverts to `defer free(content)` — no buffer transfer
  needed now that `parse` owns its copies
- `Model.saveForm` no longer pre-dupes form values, since `addHost`
  now takes ownership; this also closes a leak when the form `name`
  field was empty
- ssh_config tests for addHost switch to `std.testing.allocator`
  with `defer config.deinit(...)`, validating the ownership story
  with the leak detector
@midasdf

midasdf commented May 7, 2026

Copy link
Copy Markdown
Owner Author

さらに追加対応 — 残りの architectural issue 2件

前回サマリで「スコープ外」とした残り 2 件もユーザーリクエストで本 PR に取り込みました。

🛠 commit efb6ac7 — search/tag filter で selected と表示位置がズレる問題

Before: model.selected は `hosts.items` のインデックスとして使われたり、レンダラ内の `display_idx` 比較対象として使われたりしていて、フィルタ適用時に矛盾。moveDown も hosts.items.len を上限にしていた。

After: `Model.visible_indices: std.ArrayList(usize)` を追加し、フィルタ後の表示順を保持。レンダラはこれをそのままイテレートするだけになり、`selected` は完全に `visible_indices` のインデックス空間で管理。

  • rebuildHostList 末尾で rebuildVisibleIndices を呼ぶ
  • cycleSortMode / cycleTagFilter / search-text 変更時にも rebuildVisibleIndices
  • moveDown は visible_indices.items.len で bound check
  • connectToSelected / deleteSelectedHost / 編集 ('e') / forward ('f') / 削除確認表示 すべて visible_indices.items[selected] 経由でアクセス
  • views/host_list.zig から matchesSearch / hasTag をapp.zigに移動 (重複排除)

🛠 commit b9ba2b5 — ssh_config 文字列所有権リファクタ

Before:

  • parse() が `content` 内のスライスを `Host` フィールドや `raw_lines` にそのまま保持 (これは前回のコミットで Config.raw_buffer を持たせて延命)
  • addHost は `allocPrint` で新規行を追加するが、これらは `deinit` で個別解放されず leak
  • 既存テストはこの leak のため `page_allocator` を使い defer deinit をスキップしていた

After: Config が中の文字列すべてを単独所有:

  • parse() は host name/各フィールド/各 raw_line を deep-copy (`errdefer` で部分 OOM クリーンアップ)
  • setHostField を fallible にして dupe-then-free-old パターン (重複キーで dangle しない)
  • addHost は incoming Host と既存 lines を deep-copy → 二相コミットで toOwnedSlice 失敗時にも config を破壊しない
  • removeHost は削除対象の host string と raw_lines 要素を解放
  • Config.deinit は freeHostStrings ヘルパで全フィールド解放
  • readFile は defer free(content) に戻る (parse が必要なものは全部 dup している)
  • Model.saveForm は事前 dup 不要に — addHost が dup するから (空 name 早期 return での leak も解消)
  • 影響テスト 3 件を `std.testing.allocator` + `defer deinit` に変更

`zig build test` (リーク検出 std.testing.allocator 経由) パスを確認しました。

📊 PR 全体サマリ

種別 件数
✅ Migration scope fix 8 件 (commit 3f625e2)
✅ Pre-existing bug fix (review 指摘) 5 件 (commit 316e53b)
✅ Architectural fix (filter 整合性) 1 件 (commit efb6ac7)
✅ Architectural fix (ssh_config 所有権) 1 件 (commit b9ba2b5)
❌ False positive (push back 済) 4 件 (build.zig.zon hash)

`zig build` / `zig build test` / `--help` / `--version` 全部通過、TUI smoke OK。

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b9ba2b5dbb

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/app.zig
if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {};
}
meta_mod.writeFile(self.pa, &self.meta_store, self.meta_path) catch {};
self.meta_store.setTags(self.pa, name, tags.items) catch {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rebind tag filters after tag updates

When a tag filter is active, tag_filter points at one of the tag strings owned by meta_store; saving this form now always calls setTags, which frees the old tag slices for the edited host before rebuildHostList() immediately evaluates the still-active filter. Editing or clearing the currently filtered tag can therefore compare against freed memory, and if the tag list becomes empty the user cannot cycle the filter off because cycleTagFilter returns early. Reset or rebind tag_filter/tag_filter_index after updating tags and before rebuilding the visible list.

Useful? React with 👍 / 👎.

@midasdf
midasdf merged commit 913078a into master May 7, 2026
5 checks passed
@midasdf
midasdf deleted the claude/update-sshz-zig-0.16-EDHxe branch May 7, 2026 13:58
midasdf added a commit that referenced this pull request May 7, 2026
Bump version to 1.1.0 covering changes since v1.0.0:
- Migrate to Zig 0.16 + zigzag v0.1.5 (#3)
- Add CI and Zig security audit workflow (#1)
- Add Zig install instructions to README
- Add LLM-generated code disclaimer
- Update binary size figures and Zig version requirement

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants