Repository navigation
chore: update to zig 0.16 and zigzag v0.1.5 - #3
Conversation
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 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 · |
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughZig を 0.16.0 に上げ、std.Io と std.process.Init を注入してファイルIO・プロセス生成・スレッド同期・タイムスタンプ取得を IO 経由で一元化するリファクタリングです。 変更内容Zig 0.16.0 と IO 統合リファクタリング
🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
|
|
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.
Up to standards ✅🟢 Issues
|
| .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", | ||
| .hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv", |
There was a problem hiding this comment.
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 fixThere was a problem hiding this comment.
検証しました。この指摘は 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 で問題なく成功します。
There was a problem hiding this comment.
✅ 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
| .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", | ||
| .hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv", |
There was a problem hiding this comment.
🔴 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 fixThere was a problem hiding this comment.
検証しました。この指摘は 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 で問題なく成功します。
There was a problem hiding this comment.
✅ Customized review instruction saved!
Instruction:
For Zig
build.zig.zondependency updates, do not flag a mismatch based only on the hash prefix version; verify the dependency withzig fetch/zig buildfirst, 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
There was a problem hiding this comment.
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.
| .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", |
There was a problem hiding this comment.
検証しました。この指摘は 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 で問題なく成功します。
|
|
||
| std.fs.cwd().makePath(dir_path) catch {}; | ||
| const cwd = std.Io.Dir.cwd(); | ||
| cwd.createDirPath(io, dir_path) catch {}; |
There was a problem hiding this comment.
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;
There was a problem hiding this comment.
Fixed in 3f625e2。try cwd.createDirPath(io, dir_path) に変更しました。createDirPath は仕様上、既存ディレクトリでは成功を返す(PathAlreadyExists を返さない)ため、ガード分岐なしで素直に try で propagate しています。
| 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 {}; |
There was a problem hiding this comment.
There was a problem hiding this comment.
Fixed in 3f625e2。backupFile の createDirPath を try に変更しました。同上の理由で PathAlreadyExists ガードは省略しています。
| 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; |
There was a problem hiding this comment.
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();
There was a problem hiding this comment.
Fixed in 3f625e2。createFile/writeAll/flush を try に変更し、!void でのエラー伝搬に揃えました。呼び出し側 (writeFile) で backupFile(...) catch {} がベストエフォート扱いするのは従来通りです。
| const to_delete = entries.items.len - 10; | ||
| for (entries.items[0..to_delete]) |name| { | ||
| dir.deleteFile(name) catch {}; | ||
| dir.deleteFile(io, name) catch {}; |
There was a problem hiding this comment.
There was a problem hiding this comment.
Fixed in 3f625e2。try dir.deleteFile(io, name) に変更しました。
| 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); |
There was a problem hiding this comment.
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 fixThere was a problem hiding this comment.
Fixed in 3f625e2。toOwnedSlice の OOM 経路で unlock してから return するよう修正しました:
const threads = self.threads.toOwnedSlice(self.allocator) catch {
self.threads_mutex.unlock(self.io);
return;
};There was a problem hiding this comment.
💡 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".
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3f625e2。std.Io.net.IpAddress.parse を先に試して、IP リテラル (IPv4/IPv6) は HostName.init をバイパスして直接 addr.connect(io, ...) する経路を追加しました。これで ::1 や 2001:db8::1 のようなホスト名でもステータスチェックが通るようになります。
| 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 {}; |
There was a problem hiding this comment.
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 fixThere was a problem hiding this comment.
ご指摘内容は正しいですが、これは 本 PR で導入されたバグではなく master 時点から存在する既存バグ です (git diff master..HEAD -- src/app.zig で確認、connectToSelected の変更は IO 引数の追加のみ)。本 PR は Zig 0.16 への migration がスコープなので、ロジックの重複呼び出しの整理は別 PR で対応するのが適切と判断しました。修正案 (TUI 側の recordConnection を削除し directConnect 側に集約) は別 issue として追跡します。
There was a problem hiding this comment.
✅ 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
There was a problem hiding this comment.
Fixed in 316e53b。connectToSelected 側の recordConnection + writeFile を削除し、directConnect (TUI 終了後に呼ばれる) のみが記録するようにしました。これで TUI 経由の接続でも connect_count が二重インクリメントされなくなります。
別 PR で対応する旨の前回コメントを撤回し、本 PR で取り込みました (ユーザーリクエスト)。
| } | ||
|
|
||
| // sshz <host> [command...] — direct connect | ||
| if (args.len >= 2 and args[1][0] != '-') { |
There was a problem hiding this comment.
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| var dir_fd = try cwd.openDir(io, dir_path, .{}); | ||
| defer dir_fd.close(io); |
There was a problem hiding this comment.
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 fixThere was a problem hiding this comment.
Fixed in 3f625e2。writeFile で openDir の前に try cwd.createDirPath(io, dir_path) を呼ぶよう修正しました (meta.zig の writeFile と同じパターン)。
|
CodeAnt AI finished reviewing your PR. |
There was a problem hiding this comment.
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 liftJSON を手組みしているので文字列内容で壊れます。
ホスト名、タグ、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
📒 Files selected for processing (14)
.github/workflows/ci.yml.gitignorebuild.zig.zonsrc/app.zigsrc/checker.zigsrc/main.zigsrc/meta.zigsrc/ssh_config.zigsrc/utils.zigsrc/views/forward.zigsrc/views/help.zigsrc/views/host_form.zigsrc/views/host_list.zigtests/test_meta.zig
| .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", | ||
| .hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv", |
There was a problem hiding this comment.
🧩 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 に修正するよう報告してください。
There was a problem hiding this comment.
検証しました。この指摘は 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 で問題なく成功します。
There was a problem hiding this comment.
@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.
- 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
レビュー対応サマリ (commit 3f625e2)✅ Fixed (migration scope)
❌ False positive — push back
⏭ Out of scope — pre-existing bugs (別 PR/issue で対応)
それぞれの修正案は各レビューコメントに記載されている通りで、別 PR で個別対応します。 |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/checker.zigsrc/main.zigsrc/meta.zigsrc/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
| 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(); |
There was a problem hiding this comment.
🧩 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:
- 1: https://git.medv.io/zig/commit/ebcc6f166c9c34d00b750f26687c9ee36b243cb0.html
- 2: std.Io.Clock.now does not return nanoseconds on Windows when using the
awakeorbootclocks ziglang/zig#26014
🏁 Script executed:
#!/bin/bash
# std.Io.Timestamp の定義と toSeconds/now メソッドを検索
rg -n "Timestamp" --type=zig -C 3Repository: 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.
| } | ||
|
|
||
| try dir_fd.rename(tmp_name, basename); | ||
| try dir_fd.rename(tmp_name, dir_fd, basename, io); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# std.Io.Dir.rename のシグネチャを検索
rg -n "fn rename" --type=zig -C 5Repository: midasdf/sshz
Length of output: 38
🏁 Script executed:
cd /tmp && find . -name "src" -type d 2>/dev/null | head -5Repository: midasdf/sshz
Length of output: 38
🏁 Script executed:
git ls-files | head -20Repository: 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 2Repository: midasdf/sshz
Length of output: 349
🏁 Script executed:
rg "rename" --type zigRepository: midasdf/sshz
Length of output: 198
🏁 Script executed:
cat -n build.zigRepository: 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 -40Repository: midasdf/sshz
Length of output: 1727
🏁 Script executed:
rg "io" src/meta.zig | head -20Repository: 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 3Repository: 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.
| 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)
追加対応 — pre-existing バグも修正 (commit 316e53b)前のサマリで「別 PR で対応」とした 5 件、すべて本 PR に取り込みました (ユーザーリクエスト)。 修正内容
注意事項
各 inline スレッド (#3199706426, #3199746314) にも対応コメントを追記済みです。 |
There was a problem hiding this comment.
💡 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".
| return .online; | ||
| } else |_| {} | ||
|
|
||
| const host = std.Io.net.HostName.init(hostname) catch return .offline; |
There was a problem hiding this comment.
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 👍 / 👎.
…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
さらに追加対応 — 残りの architectural issue 2件前回サマリで「スコープ外」とした残り 2 件もユーザーリクエストで本 PR に取り込みました。 🛠 commit
|
| 種別 | 件数 |
|---|---|
| ✅ 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。
There was a problem hiding this comment.
💡 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".
| 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 {}; |
There was a problem hiding this comment.
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 👍 / 👎.
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>
User description
Migrates sshz to Zig 0.16's reworked I/O model, where filesystem,
process, and network operations require an
Ioinstance. The mainentry point now takes
std.process.Init, andioplusenviron_mapare threaded through ssh_config, meta, app, and checker.
Notable changes:
std.process.spawn(io, ...)replacesstd.process.Child.initstd.Io.File.stdout()replacesstd.fs.File{ .handle = ... }init.minimal.args.toSlice(arena)replacesargsAlloc/argsFreestd.Io.Dir.cwd()with buffered writersand
init.environ_map.get("HOME")for env accessstd.Io.net.HostName.connect(io, port, .{})for TCPstatus checks
zz.Color.cyan/whiteare now consts (not functions)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
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:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
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:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
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
Bug Fixes / 信頼性向上
UI