Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ Codex CLI and Claude Code sessions are captured by learner-server's `clients/upl
(learner-upload), not by this app (yet): it tails `~/.codex/sessions` and
`~/.claude/projects` and uploads the raw session files with the same device key and client id.

The app also wires learner-server's live hook into Claude Code on this Mac (job `ClaudeHook`,
at launch and every 6 hours): it runs learner-server's `clients/hook/src/install.ts` from the
same checkout as the uploader, pointed at the paired server and at the Keychain lookup for the
device key (the key is never passed or written), then the installer's `--check`. That puts the
hook in the user-level `~/.claude/settings.json`, so it runs in every Claude Code session in
any folder: the terminal CLI and the Code tab of the Claude desktop app, which runs the same
Claude Code. A chat in the Claude desktop app or on claude.ai runs no hooks; those
conversations reach the server afterwards through the chat archive. A checkout from before
the installer existed is fast-forwarded once (only when it has no local changes).

## Pairing with learner-server

Everything goes to learner-server over HTTPS as `POST ${LEARNER_API_URL}/rpc/<name>` with body
Expand Down
62 changes: 62 additions & 0 deletions Tests/HeavyTests/PairingE2ETests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,68 @@ struct PairingE2ETests {
#expect(!keyLogged, "the key is never logged")
}

/// The Claude Code hook, wired by the app's own job with learner-server's real installer
/// and a real device key, into a scratch ~/.claude (never the machine's own): the
/// installer's check passes against the server, and a prompt sent through the installed
/// hook command comes back carrying the live-feedback instructions. Needs the server
/// checkout on this machine (the runner), since the installer is run from it.
@Test(.enabled(if: Harness.localServer != nil, "needs the local harness (LEARNER_SERVER_DIR): the installer runs from that checkout"))
func theHookJobWiresClaudeCodeAndAPromptReachesTheServer() throws {
let server = try #require(Harness.localServer)
let harness = try Harness(["--topology", "same-machine"])
defer { harness.stop() }
let ready = try #require(harness.ready(), "the harness did not start: \(harness.output.suffix(1500))")
let pairingPath = try #require(ready["pairingFile"] as? String)
let data = try #require(harness.pairingFile(pairingPath))
guard case .success(let p) = Pairing.parse(data) else { Issue.record("the harness's payload does not parse"); return }

// The key reaches the hook from a mode-600 file in the scratch folder (the Keychain's
// stand-in here: LEARNER_HOOK_KEY_FILE outranks the configured Keychain lookup).
let home = TempDir("claude-hook-e2e")
let keyFile = home.write("device-key.env", "LEARNER_API_KEY=\(p.apiKey)\n", mode: 0o600)
let scratch = ["LEARNER_HOOK_CONFIG": home.file(".claude/learning-hook.json"),
"LEARNER_HOOK_TRACE_DIR": home.file(".claude/learner-hook-traces"),
"LEARNER_HOOK_KEY_FILE": keyFile]
var c = ClaudeHook.Config()
c.jobName = "test-claude-hook-e2e-\(UUID().uuidString.prefix(8))"
defer { try? FileManager.default.removeItem(atPath: Job.stateDir + "/\(c.jobName).json") }
c.repo = server
c.bun = Live.env["LEARNER_BUN"] ?? "/opt/homebrew/bin/bun"
c.serverURL = { p.apiUrl }
c.clientId = { p.clientId }
c.paired = { true }
c.environment = scratch
c.updateCheckout = false
let outcome = ClaudeHook(config: c).runOnce()
guard case .ok(let summary, _) = outcome else { Issue.record("the hook job did not finish ok: \(outcome)"); return }
#expect(summary.hasPrefix("wired into Claude Code"))

// What it wrote: user-level settings with the hook on every event, and a config that
// names the server and the Keychain lookup, not the key.
let settings = try #require(try? JSONSerialization.jsonObject(with: Data(home.read(".claude/settings.json").utf8)) as? [String: Any])
let hooks = try #require(settings["hooks"] as? [String: [[String: Any]]])
for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] { #expect(hooks[event]?.isEmpty == false, "no \(event) hook") }
let config = home.read(".claude/learning-hook.json")
#expect(config.contains(p.apiUrl) && config.contains("find-generic-password"))
let keyWritten = (config + home.read(".claude/settings.json")).contains(p.apiKey)
#expect(!keyWritten, "the key is never written into Claude Code's files")

// One prompt, through the command Claude Code would run.
let command = try #require(((hooks["UserPromptSubmit"]?.first?["hooks"] as? [[String: Any]])?.first)?["command"] as? String)
// A bare UUID: the hook validates session_id as one and stays silent (fails open) otherwise.
let session = UUID().uuidString.lowercased()
let prompt = try JSONSerialization.data(withJSONObject: ["hook_event_name": "UserPromptSubmit", "session_id": session,
"prompt": "Explain why a B-tree index speeds up this lookup."])
let turn = ChildProcess.run("/bin/sh", ["-c", command], timeout: 30,
env: ChildProcess.toolEnvironment.merging(scratch) { _, new in new }, input: prompt)
#expect(turn.status == 0)
// Bools first: a failed #expect prints its operands, and this log is public.
let taught = turn.output.contains("LEARNING LIVE FEEDBACK") && turn.output.contains(session)
#expect(taught, "the hook did not return live feedback for the prompt")
let keyPrinted = turn.output.contains(p.apiKey)
#expect(!keyPrinted, "the key is never printed")
}

static let installedBinary = NSHomeDirectory() + "/Applications/Learner Desktop.app/Contents/MacOS/learner-desktop"

@Test func pairsWithAServerOnTheSameMachine() throws {
Expand Down
54 changes: 54 additions & 0 deletions Tests/LightTests/ClaudeHookTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation
import Testing
@testable import LearnerDesktop
import TestSupport

// The Claude Code hook job's pure parts: what it asks learner-server's installer to do, and
// what the installer's --check report means for the tray.
@Suite("Claude Code hook", .tags(.light, .sessions), .timeLimit(.minutes(1)), .quietLog) struct ClaudeHookTests {
@Test func theInstallerIsToldHowToReadTheKeyNeverTheKey() throws {
let args = ClaudeHook.installArguments(installer: "/r/clients/hook/src/install.ts", bun: "/h/.bun/bin/bun",
serverURL: "https://learner.example/learner-api", clientId: "a-mac")
#expect(args.prefix(5) == ["/r/clients/hook/src/install.ts", "--bun", "/h/.bun/bin/bun", "--server-url", "https://learner.example/learner-api"])
#expect(args[5] == "--key-command-json" && args.count == 7)
let command = try #require(try? JSONSerialization.jsonObject(with: Data(args[6].utf8)) as? [String])
#expect(command == ["/usr/bin/security", "find-generic-password", "-s", "learner-server", "-a", "a-mac", "-w"])
// The same lookup the app itself uses for its own calls.
#expect(command == ClaudeHook.keyCommand(clientId: "a-mac"))
#expect(!args[6].contains("\\"), "plain slashes, as a person would write it")
let more = ClaudeHook.installArguments(installer: "i", bun: "b", serverURL: "u", clientId: "c", catalogParts: 7)
#expect(more.suffix(2) == ["--catalog-parts", "7"])
}

@Test func theCheckReportIsTheLastJSONLine() throws {
let text = """
bun: a notice that is not the report
{"ok":true,"settings":"/h/.claude/settings.json","events":{"Stop":true},"catalogParts":5,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogPartsNeeded":5}

"""
let c = try #require(ClaudeHook.parseCheck(text))
#expect(c == ClaudeHook.Check(ok: true, installed: true, permissions: true, config: "ok", server: "ok", catalogParts: 5, catalogPartsNeeded: 5))
#expect(ClaudeHook.parseCheck("not json\n{\"installed\":true}\n") == nil, "an install report is not a check report")
#expect(ClaudeHook.parseCheck("") == nil)
}

@Test func eachReportBecomesTheRightOutcome() {
func outcome(_ change: (inout ClaudeHook.Check) -> Void) -> String {
var c = ClaudeHook.Check(ok: false, installed: true, permissions: true, config: "ok", server: "ok", catalogParts: 5, catalogPartsNeeded: 5)
change(&c)
return describe(ClaudeHook.outcome(c))
}
#expect(outcome { $0.ok = true } == "ok: wired into Claude Code (5 catalog parts)")
// Needs the owner: blocked, not retried in a loop.
#expect(outcome { $0.server = "refused (HTTP 403)" }.hasPrefix("blocked: learner-server refused the device key"))
#expect(outcome { $0.server = "no credential" }.hasPrefix("blocked: the Claude Code hook cannot read the device key"))
// Passing trouble: retried.
#expect(outcome { $0.server = "unreachable" } == "failed: the Claude Code hook cannot reach learner-server (unreachable)")
#expect(outcome { $0.server = "error (HTTP 500)" }.hasPrefix("failed: the Claude Code hook cannot reach learner-server"))
#expect(outcome { $0.installed = false }.hasPrefix("failed: the hook is not fully wired"))
#expect(outcome { $0.permissions = false }.hasPrefix("failed: the hook is not fully wired"))
#expect(outcome { $0.config = "invalid" }.contains("learning-hook.json) is invalid"))
#expect(outcome { $0.catalogPartsNeeded = 9 } == "failed: the hook carries 5 catalog parts; the server needs 9")
#expect(describe(ClaudeHook.outcome(nil)) == "failed: the hook check printed no report")
}
}
108 changes: 108 additions & 0 deletions Tests/MediumTests/ClaudeHookJobTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import Foundation
import Testing
@testable import LearnerDesktop
import TestSupport

// The Claude Code hook job with a stand-in bun (a shell script that records what it was
// asked and answers like learner-server's installer): when it runs the installer, what it
// passes, and what each answer does to the job.
private final class HookFixture {
static let wired = #"{"ok":true,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":5,"catalogPartsNeeded":5}"#
let dir = TempDir("claude-hook")
let name = "test-claude-hook-\(UUID().uuidString.prefix(8))"
let hook: ClaudeHook

/// `checks`: what successive --check runs print, the last one repeating.
init(checkout: Bool = true, installer: Bool = true, paired: Bool = true, installExit: Int = 0, checks: [String] = [HookFixture.wired]) {
if checkout { dir.write("repo/clients/uploader/src/index.ts", "") }
if installer { dir.write("repo/clients/hook/src/install.ts", "") }
for (n, text) in checks.enumerated() { dir.write("check.\(n)", text + "\n") }
let bun = dir.write("bin/bun", """
#!/bin/bash
here="\(dir.path)"
printf '%s\\n' "$*" >> "$here/calls"
env | grep -c '^LEARNER_API_KEY=' >> "$here/key-in-env"
case "$*" in
*--check*)
n=$(cat "$here/checked" 2>/dev/null || echo 0)
echo $((n + 1)) > "$here/checked"
[ -f "$here/check.$n" ] || n=\(checks.count - 1)
cat "$here/check.$n" ;;
*) echo '{"installed":true}'; echo "learner hook install failed: settings are not a JSON object" >&2; exit \(installExit) ;;
esac
""", executable: true)
var c = ClaudeHook.Config()
c.jobName = name
c.repo = dir.file("repo")
c.bun = bun
c.git = "/usr/bin/false"
c.serverURL = { "https://learner.example/learner-api" }
c.clientId = { "a-mac" }
c.paired = { paired }
c.timeout = 20
c.updateCheckout = false
hook = ClaudeHook(config: c)
}

deinit { try? FileManager.default.removeItem(atPath: Job.stateDir + "/\(name).json") }

var calls: [String] { dir.read("calls").split(separator: "\n").map(String.init) }
}

@Suite("Claude Code hook job (stand-in bun, real processes)", .tags(.medium, .sessions), .quietLog, .serialized, .timeLimit(.minutes(1))) struct ClaudeHookJobTests {
@Test func itInstallsThenChecksAndNamesOnlyTheKeychainLookup() {
let f = HookFixture()
#expect(describe(f.hook.runOnce()) == "ok: wired into Claude Code (5 catalog parts)")
#expect(f.calls.count == 2)
let install = f.calls.first ?? ""
#expect(install.hasPrefix(f.dir.file("repo/clients/hook/src/install.ts") + " --bun " + f.dir.file("bin/bun") + " --server-url https://learner.example/learner-api --key-command-json "))
#expect(install.contains(#"["/usr/bin/security","find-generic-password","-s","learner-server","-a","a-mac","-w"]"#))
#expect(f.calls.last == f.dir.file("repo/clients/hook/src/install.ts") + " --check")
}

@Test func nothingRunsWithoutACheckoutOrAPairing() {
let none = HookFixture(checkout: false, installer: false)
#expect(describe(none.hook.runOnce()) == "idle")
let unpaired = HookFixture(paired: false)
#expect(describe(unpaired.hook.runOnce()) == "idle")
#expect(none.calls.isEmpty && unpaired.calls.isEmpty)
}

@Test func aCheckoutFromBeforeTheInstallerIsBlockedWithWhatToDo() {
let f = HookFixture(installer: false)
let said = describe(f.hook.runOnce())
#expect(said.hasPrefix("blocked: the learner-server checkout") && said.hasSuffix("update it with git pull"))
#expect(f.calls.isEmpty)
}

@Test func aFailedInstallIsRetriedAndSaysWhy() {
let f = HookFixture(installExit: 1)
#expect(describe(f.hook.runOnce()) == "failed: the hook installer failed: learner hook install failed: settings are not a JSON object")
#expect(f.calls.count == 1, "no check after a failed install")
}

@Test func aRefusedKeyBlocksAndAnUnreachableServerIsRetried() {
let refused = HookFixture(checks: [#"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"refused (HTTP 403)","catalogParts":5}"#])
#expect(describe(refused.hook.runOnce()).hasPrefix("blocked: learner-server refused the device key"))
let down = HookFixture(checks: [#"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"unreachable","catalogParts":5}"#])
#expect(describe(down.hook.runOnce()).hasPrefix("failed: the Claude Code hook cannot reach learner-server"))
}

@Test func aBiggerCatalogGetsAsManyCompanionsAsItNeeds() {
let f = HookFixture(checks: [
#"{"ok":false,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":5,"catalogPartsNeeded":7}"#,
#"{"ok":true,"installed":true,"permissions":true,"config":"ok","server":"ok","catalogParts":7,"catalogPartsNeeded":7}"#,
])
#expect(describe(f.hook.runOnce()) == "ok: wired into Claude Code (7 catalog parts)")
#expect(f.calls.count == 4)
#expect(f.calls[2].hasSuffix(" --catalog-parts 7"))
}

@Test func theInstallerNeverGetsTheKeyInItsEnvironment() {
let f = HookFixture()
_ = f.hook.runOnce()
// Unless the test process itself was started with one (it is not, in any lane).
let leaked = f.dir.read("key-in-env").split(separator: "\n").contains { $0 != "0" }
#expect(leaked == (ProcessInfo.processInfo.environment["LEARNER_API_KEY"] != nil))
}
}
2 changes: 1 addition & 1 deletion config/learner-server.ref
Original file line number Diff line number Diff line change
@@ -1 +1 @@
84fb766b51611fd54d0b3d8c22d0372cc18109d9
6eb8c4674c7ce2182e6ac5b234821cdf8bb1d9f3
Loading
Loading