2026-02-20 22:55:49 +01:00
use serde ::{ Deserialize , Serialize } ;
#[ derive(Debug, Deserialize) ]
pub struct AiChatRequest {
pub model : Option < String > ,
pub messages : Vec < AiMessage > ,
pub system : Option < String > ,
pub max_tokens : Option < u32 > ,
}
#[ derive(Debug, Deserialize, Serialize, Clone) ]
pub struct AiMessage {
pub role : String ,
pub content : String ,
}
#[ derive(Debug, Serialize) ]
pub struct AiChatResponse {
pub content : String ,
pub model : String ,
pub stop_reason : Option < String > ,
}
#[ derive(Debug, Deserialize) ]
struct AnthropicResponse {
content : Vec < ContentBlock > ,
model : String ,
stop_reason : Option < String > ,
}
#[ derive(Debug, Deserialize) ]
struct ContentBlock {
text : Option < String > ,
}
#[ derive(Debug, Serialize) ]
struct AnthropicRequest {
model : String ,
max_tokens : u32 ,
messages : Vec < AiMessage > ,
#[ serde(skip_serializing_if = " Option::is_none " ) ]
system : Option < String > ,
}
fn get_api_key ( ) -> Result < String , String > {
std ::env ::var ( " ANTHROPIC_API_KEY " )
. map_err ( | _ | " ANTHROPIC_API_KEY environment variable not set " . to_string ( ) )
}
fn build_request ( req : & AiChatRequest ) -> AnthropicRequest {
AnthropicRequest {
feat: auto-build, GitHub Release, and in-app updater (#14)
* ci: auto-release workflow on merge to main
Rewrite .github/workflows/release.yml to trigger on every push to main
instead of manual tag pushes. The workflow now:
- Computes version as 0.YYYYMMDD.GITHUB_RUN_NUMBER
- Builds aarch64-apple-darwin and x86_64-apple-darwin in parallel
- Merges them into a universal binary using lipo
- Creates a universal .dmg and signed updater tarball
- Generates latest.json with per-arch and universal platform entries
- Publishes a GitHub Release with auto-generated release notes
- Updates a GitHub Pages release history site (gh-pages branch)
Product decisions:
- Universal binary approach: copy arm64 .app as base, lipo the main
executable, keep everything else from arm64 (shared frameworks are
architecture-independent). This is the standard Tauri pattern.
- Per-arch updater tarballs are also uploaded so the Tauri updater can
download the correct arch-specific build (smaller download).
- Release notes are auto-generated from git log since last tag.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* ci: github pages with release history
Use peaceiris/actions-gh-pages@v4 to deploy a release history site.
The page fetches releases.json (also deployed) and renders each release
with date, notes, and download links for .dmg files.
This handles the gh-pages branch creation automatically on first run.
The page is available at https://refactoringhq.github.io/laputa-app/
Product decision: used fetch() to load releases.json at runtime instead
of inlining it, which is cleaner and avoids shell escaping issues with
release note content. The releases.json is deployed alongside index.html.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: in-app update notification UI
Replace the old window.confirm updater with a proper React-based
update notification system:
- useUpdater hook now exposes state machine (idle → available →
downloading → ready) and actions (startDownload, openReleaseNotes,
dismiss)
- UpdateBanner component renders at the top of the app shell:
- "Available" state: shows version, Release Notes link, Update Now
button, dismiss X
- "Downloading" state: animated spinner, progress bar with percentage
- "Ready" state: Restart Now button to apply the update
- Silently checks on startup after 3s delay; fails silently on
network errors or 404
- Release Notes link opens the GitHub Pages release history site
Product decisions:
- Banner at top of app (not a modal) — non-intrusive, visible but
not blocking. User can dismiss and continue working.
- Progress bar shows during download so user knows it's working.
- Separate "Restart Now" state after download so user controls when
the app restarts (they may have unsaved work).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: updater component tests
Rewrite useUpdater hook tests and add UpdateBanner component tests:
Hook tests (10 cases):
- Starts in idle state
- Does nothing when not in Tauri
- Checks for updates after 3s delay
- Stays idle when no update available
- Transitions to available when update found
- Handles missing release body gracefully
- Stays idle on network error (fails silently)
- Dismiss returns to idle
- openReleaseNotes opens correct URL
- startDownload transitions through downloading to ready
Component tests (10 cases):
- Renders nothing when idle
- Renders nothing on error
- Shows version and buttons when available
- Update Now calls startDownload
- Release Notes calls openReleaseNotes
- Dismiss button works
- Shows progress bar during download
- Shows 0% at start of download
- Shows restart button when ready
- Restart button calls restartApp
All 457 tests pass.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* design: auto-build-release wireframes
Copy ui-design.pen as base. Frames to be added for:
1. Update notification banner (visible state) — horizontal bar at
top of app shell with version text, Release Notes link, Update
Now button, and dismiss X
2. Update download progress state — spinner icon, progress bar with
percentage, downloading text
3. "Restart to apply" state — green accent, version text, Restart
Now button
Note: Pencil editor was not available during this session. The base
design file is committed; frames will be added when the editor is
accessible. The implemented component (UpdateBanner.tsx) serves as
the source of truth for the design.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: update ARCHITECTURE.md with release/update system
Add comprehensive documentation for:
- Release pipeline (4-phase workflow: version → build → release → pages)
- Versioning scheme (0.YYYYMMDD.RUN_NUMBER)
- Universal binary strategy (lipo merge)
- Updater endpoint and latest.json manifest
- In-app update UI state machine
- GitHub Pages release history site
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: rustfmt formatting
* fix: rustfmt build.rs
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:50:36 +01:00
model : req
. model
. clone ( )
. unwrap_or_else ( | | " claude-3-5-haiku-20241022 " . to_string ( ) ) ,
2026-02-20 22:55:49 +01:00
max_tokens : req . max_tokens . unwrap_or ( 4096 ) ,
messages : req . messages . clone ( ) ,
system : req . system . clone ( ) ,
}
}
fn extract_response_text ( resp : & AnthropicResponse ) -> String {
resp . content
. iter ( )
. filter_map ( | block | block . text . as_ref ( ) )
. cloned ( )
. collect ::< Vec < _ > > ( )
. join ( " " )
}
pub async fn send_chat ( req : AiChatRequest ) -> Result < AiChatResponse , String > {
let api_key = get_api_key ( ) ? ;
2026-02-23 20:47:09 +01:00
send_chat_with_base ( req , " https://api.anthropic.com " , & api_key ) . await
}
async fn send_chat_with_base (
req : AiChatRequest ,
api_base : & str ,
api_key : & str ,
) -> Result < AiChatResponse , String > {
2026-02-20 22:55:49 +01:00
let anthropic_req = build_request ( & req ) ;
let client = reqwest ::Client ::new ( ) ;
let response = client
2026-02-23 20:47:09 +01:00
. post ( format! ( " {} /v1/messages " , api_base ) )
. header ( " x-api-key " , api_key )
2026-02-20 22:55:49 +01:00
. header ( " anthropic-version " , " 2023-06-01 " )
. header ( " content-type " , " application/json " )
. json ( & anthropic_req )
. send ( )
. await
. map_err ( | e | format! ( " Request failed: {} " , e ) ) ? ;
if ! response . status ( ) . is_success ( ) {
let status = response . status ( ) ;
let body = response . text ( ) . await . unwrap_or_default ( ) ;
return Err ( format! ( " Anthropic API error ( {} ): {} " , status , body ) ) ;
}
let anthropic_resp : AnthropicResponse = response
. json ( )
. await
. map_err ( | e | format! ( " Failed to parse response: {} " , e ) ) ? ;
Ok ( AiChatResponse {
content : extract_response_text ( & anthropic_resp ) ,
model : anthropic_resp . model ,
stop_reason : anthropic_resp . stop_reason ,
} )
}
#[ cfg(test) ]
mod tests {
use super ::* ;
2026-02-23 20:47:09 +01:00
// ── Pure logic tests ─────────────────────────────────────────────────────
2026-02-20 22:55:49 +01:00
#[ test ]
fn test_build_request_defaults ( ) {
let req = AiChatRequest {
model : None ,
messages : vec ! [ AiMessage {
role : " user " . to_string ( ) ,
content : " Hello " . to_string ( ) ,
} ] ,
system : None ,
max_tokens : None ,
} ;
let built = build_request ( & req ) ;
assert_eq! ( built . model , " claude-3-5-haiku-20241022 " ) ;
assert_eq! ( built . max_tokens , 4096 ) ;
assert! ( built . system . is_none ( ) ) ;
}
#[ test ]
fn test_build_request_custom ( ) {
let req = AiChatRequest {
model : Some ( " claude-sonnet-4-20250514 " . to_string ( ) ) ,
messages : vec ! [ ] ,
system : Some ( " You are helpful " . to_string ( ) ) ,
max_tokens : Some ( 1024 ) ,
} ;
let built = build_request ( & req ) ;
assert_eq! ( built . model , " claude-sonnet-4-20250514 " ) ;
assert_eq! ( built . max_tokens , 1024 ) ;
assert_eq! ( built . system . unwrap ( ) , " You are helpful " ) ;
}
#[ test ]
fn test_extract_response_text ( ) {
let resp = AnthropicResponse {
content : vec ! [
feat: auto-build, GitHub Release, and in-app updater (#14)
* ci: auto-release workflow on merge to main
Rewrite .github/workflows/release.yml to trigger on every push to main
instead of manual tag pushes. The workflow now:
- Computes version as 0.YYYYMMDD.GITHUB_RUN_NUMBER
- Builds aarch64-apple-darwin and x86_64-apple-darwin in parallel
- Merges them into a universal binary using lipo
- Creates a universal .dmg and signed updater tarball
- Generates latest.json with per-arch and universal platform entries
- Publishes a GitHub Release with auto-generated release notes
- Updates a GitHub Pages release history site (gh-pages branch)
Product decisions:
- Universal binary approach: copy arm64 .app as base, lipo the main
executable, keep everything else from arm64 (shared frameworks are
architecture-independent). This is the standard Tauri pattern.
- Per-arch updater tarballs are also uploaded so the Tauri updater can
download the correct arch-specific build (smaller download).
- Release notes are auto-generated from git log since last tag.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* ci: github pages with release history
Use peaceiris/actions-gh-pages@v4 to deploy a release history site.
The page fetches releases.json (also deployed) and renders each release
with date, notes, and download links for .dmg files.
This handles the gh-pages branch creation automatically on first run.
The page is available at https://refactoringhq.github.io/laputa-app/
Product decision: used fetch() to load releases.json at runtime instead
of inlining it, which is cleaner and avoids shell escaping issues with
release note content. The releases.json is deployed alongside index.html.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: in-app update notification UI
Replace the old window.confirm updater with a proper React-based
update notification system:
- useUpdater hook now exposes state machine (idle → available →
downloading → ready) and actions (startDownload, openReleaseNotes,
dismiss)
- UpdateBanner component renders at the top of the app shell:
- "Available" state: shows version, Release Notes link, Update Now
button, dismiss X
- "Downloading" state: animated spinner, progress bar with percentage
- "Ready" state: Restart Now button to apply the update
- Silently checks on startup after 3s delay; fails silently on
network errors or 404
- Release Notes link opens the GitHub Pages release history site
Product decisions:
- Banner at top of app (not a modal) — non-intrusive, visible but
not blocking. User can dismiss and continue working.
- Progress bar shows during download so user knows it's working.
- Separate "Restart Now" state after download so user controls when
the app restarts (they may have unsaved work).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: updater component tests
Rewrite useUpdater hook tests and add UpdateBanner component tests:
Hook tests (10 cases):
- Starts in idle state
- Does nothing when not in Tauri
- Checks for updates after 3s delay
- Stays idle when no update available
- Transitions to available when update found
- Handles missing release body gracefully
- Stays idle on network error (fails silently)
- Dismiss returns to idle
- openReleaseNotes opens correct URL
- startDownload transitions through downloading to ready
Component tests (10 cases):
- Renders nothing when idle
- Renders nothing on error
- Shows version and buttons when available
- Update Now calls startDownload
- Release Notes calls openReleaseNotes
- Dismiss button works
- Shows progress bar during download
- Shows 0% at start of download
- Shows restart button when ready
- Restart button calls restartApp
All 457 tests pass.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* design: auto-build-release wireframes
Copy ui-design.pen as base. Frames to be added for:
1. Update notification banner (visible state) — horizontal bar at
top of app shell with version text, Release Notes link, Update
Now button, and dismiss X
2. Update download progress state — spinner icon, progress bar with
percentage, downloading text
3. "Restart to apply" state — green accent, version text, Restart
Now button
Note: Pencil editor was not available during this session. The base
design file is committed; frames will be added when the editor is
accessible. The implemented component (UpdateBanner.tsx) serves as
the source of truth for the design.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: update ARCHITECTURE.md with release/update system
Add comprehensive documentation for:
- Release pipeline (4-phase workflow: version → build → release → pages)
- Versioning scheme (0.YYYYMMDD.RUN_NUMBER)
- Universal binary strategy (lipo merge)
- Updater endpoint and latest.json manifest
- In-app update UI state machine
- GitHub Pages release history site
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: rustfmt formatting
* fix: rustfmt build.rs
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:50:36 +01:00
ContentBlock {
text : Some ( " Hello " . to_string ( ) ) ,
} ,
ContentBlock {
text : Some ( " world " . to_string ( ) ) ,
} ,
2026-02-20 22:55:49 +01:00
ContentBlock { text : None } ,
] ,
model : " test " . to_string ( ) ,
stop_reason : Some ( " end_turn " . to_string ( ) ) ,
} ;
assert_eq! ( extract_response_text ( & resp ) , " Hello world " ) ;
}
2026-02-23 20:47:09 +01:00
#[ test ]
fn test_extract_response_text_empty ( ) {
let resp = AnthropicResponse {
content : vec ! [ ] ,
model : " test " . to_string ( ) ,
stop_reason : None ,
} ;
assert_eq! ( extract_response_text ( & resp ) , " " ) ;
}
#[ test ]
fn test_extract_response_text_all_none ( ) {
let resp = AnthropicResponse {
2026-02-23 21:04:15 +01:00
content : vec ! [ ContentBlock { text : None } , ContentBlock { text : None } ] ,
2026-02-23 20:47:09 +01:00
model : " test " . to_string ( ) ,
stop_reason : None ,
} ;
assert_eq! ( extract_response_text ( & resp ) , " " ) ;
}
2026-02-24 12:34:25 +01:00
// Mutex to serialize env-var tests and avoid race conditions in parallel test runs
static ENV_MUTEX : std ::sync ::Mutex < ( ) > = std ::sync ::Mutex ::new ( ( ) ) ;
2026-02-23 20:47:09 +01:00
#[ test ]
fn test_get_api_key_missing ( ) {
2026-02-24 12:34:25 +01:00
let _guard = ENV_MUTEX . lock ( ) . unwrap ( ) ;
2026-02-23 20:47:09 +01:00
// Temporarily clear the env var
let prev = std ::env ::var ( " ANTHROPIC_API_KEY " ) . ok ( ) ;
unsafe {
std ::env ::remove_var ( " ANTHROPIC_API_KEY " ) ;
}
let result = get_api_key ( ) ;
// Restore
if let Some ( val ) = prev {
unsafe {
std ::env ::set_var ( " ANTHROPIC_API_KEY " , val ) ;
}
}
assert! ( result . is_err ( ) ) ;
assert! ( result
. unwrap_err ( )
. contains ( " ANTHROPIC_API_KEY environment variable not set " ) ) ;
}
#[ test ]
fn test_get_api_key_present ( ) {
2026-02-24 12:34:25 +01:00
let _guard = ENV_MUTEX . lock ( ) . unwrap ( ) ;
2026-02-23 20:47:09 +01:00
let prev = std ::env ::var ( " ANTHROPIC_API_KEY " ) . ok ( ) ;
unsafe {
std ::env ::set_var ( " ANTHROPIC_API_KEY " , " sk-test-key-123 " ) ;
}
let result = get_api_key ( ) ;
if let Some ( val ) = prev {
unsafe {
std ::env ::set_var ( " ANTHROPIC_API_KEY " , val ) ;
}
} else {
unsafe {
std ::env ::remove_var ( " ANTHROPIC_API_KEY " ) ;
}
}
assert! ( result . is_ok ( ) ) ;
assert_eq! ( result . unwrap ( ) , " sk-test-key-123 " ) ;
}
// ── HTTP mock tests ──────────────────────────────────────────────────────
#[ tokio::test ]
async fn test_send_chat_success ( ) {
let mut server = mockito ::Server ::new_async ( ) . await ;
let mock = server
. mock ( " POST " , " /v1/messages " )
. with_status ( 200 )
. with_header ( " content-type " , " application/json " )
. with_body (
r # "{"id":"msg_01","type":"message","role":"assistant","content":[{"type":"text","text":"Hello there!"}],"model":"claude-3-5-haiku-20241022","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":5}}"# ,
)
. create_async ( )
. await ;
let req = AiChatRequest {
model : None ,
messages : vec ! [ AiMessage {
role : " user " . to_string ( ) ,
content : " Say hello " . to_string ( ) ,
} ] ,
system : None ,
max_tokens : None ,
} ;
let result = send_chat_with_base ( req , & server . url ( ) , " sk-test-key " ) . await ;
mock . assert_async ( ) . await ;
assert! ( result . is_ok ( ) ) ;
let resp = result . unwrap ( ) ;
assert_eq! ( resp . content , " Hello there! " ) ;
assert_eq! ( resp . model , " claude-3-5-haiku-20241022 " ) ;
assert_eq! ( resp . stop_reason , Some ( " end_turn " . to_string ( ) ) ) ;
}
#[ tokio::test ]
async fn test_send_chat_with_system_prompt ( ) {
let mut server = mockito ::Server ::new_async ( ) . await ;
let mock = server
. mock ( " POST " , " /v1/messages " )
. with_status ( 200 )
. with_header ( " content-type " , " application/json " )
. with_body (
r # "{"id":"msg_02","type":"message","role":"assistant","content":[{"type":"text","text":"I am a helpful assistant."}],"model":"claude-sonnet-4-20250514","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":20,"output_tokens":8}}"# ,
)
. create_async ( )
. await ;
let req = AiChatRequest {
model : Some ( " claude-sonnet-4-20250514 " . to_string ( ) ) ,
messages : vec ! [ AiMessage {
role : " user " . to_string ( ) ,
content : " Who are you? " . to_string ( ) ,
} ] ,
system : Some ( " You are a helpful assistant. " . to_string ( ) ) ,
max_tokens : Some ( 512 ) ,
} ;
let result = send_chat_with_base ( req , & server . url ( ) , " sk-key " ) . await ;
mock . assert_async ( ) . await ;
assert! ( result . is_ok ( ) ) ;
let resp = result . unwrap ( ) ;
assert_eq! ( resp . model , " claude-sonnet-4-20250514 " ) ;
assert_eq! ( resp . content , " I am a helpful assistant. " ) ;
}
#[ tokio::test ]
async fn test_send_chat_api_error ( ) {
let mut server = mockito ::Server ::new_async ( ) . await ;
let mock = server
. mock ( " POST " , " /v1/messages " )
. with_status ( 401 )
. with_header ( " content-type " , " application/json " )
. with_body ( r # "{"type":"error","error":{"type":"authentication_error","message":"Invalid API key"}}"# )
. create_async ( )
. await ;
let req = AiChatRequest {
model : None ,
messages : vec ! [ AiMessage {
role : " user " . to_string ( ) ,
content : " Hello " . to_string ( ) ,
} ] ,
system : None ,
max_tokens : None ,
} ;
let result = send_chat_with_base ( req , & server . url ( ) , " bad-key " ) . await ;
mock . assert_async ( ) . await ;
assert! ( result . is_err ( ) ) ;
let err = result . unwrap_err ( ) ;
assert! (
err . contains ( " Anthropic API error " ) & & err . contains ( " 401 " ) ,
" unexpected error: {} " ,
err
) ;
}
#[ tokio::test ]
async fn test_send_chat_rate_limit ( ) {
let mut server = mockito ::Server ::new_async ( ) . await ;
let mock = server
. mock ( " POST " , " /v1/messages " )
. with_status ( 429 )
. with_header ( " content-type " , " application/json " )
. with_body ( r # "{"type":"error","error":{"type":"rate_limit_error","message":"Rate limit exceeded"}}"# )
. create_async ( )
. await ;
let req = AiChatRequest {
model : None ,
messages : vec ! [ ] ,
system : None ,
max_tokens : None ,
} ;
let result = send_chat_with_base ( req , & server . url ( ) , " sk-key " ) . await ;
mock . assert_async ( ) . await ;
assert! ( result . is_err ( ) ) ;
let err = result . unwrap_err ( ) ;
assert! (
err . contains ( " Anthropic API error " ) & & err . contains ( " 429 " ) ,
" unexpected error: {} " ,
err
) ;
}
#[ tokio::test ]
async fn test_send_chat_multiple_content_blocks ( ) {
let mut server = mockito ::Server ::new_async ( ) . await ;
let mock = server
. mock ( " POST " , " /v1/messages " )
. with_status ( 200 )
. with_header ( " content-type " , " application/json " )
. with_body (
r # "{"id":"msg_03","type":"message","role":"assistant","content":[{"type":"text","text":"Part one. "},{"type":"text","text":"Part two."}],"model":"claude-3-5-haiku-20241022","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":5,"output_tokens":10}}"# ,
)
. create_async ( )
. await ;
let req = AiChatRequest {
model : None ,
messages : vec ! [ AiMessage {
role : " user " . to_string ( ) ,
content : " Give me two parts " . to_string ( ) ,
} ] ,
system : None ,
max_tokens : None ,
} ;
let result = send_chat_with_base ( req , & server . url ( ) , " sk-key " ) . await ;
mock . assert_async ( ) . await ;
assert! ( result . is_ok ( ) ) ;
assert_eq! ( result . unwrap ( ) . content , " Part one. Part two. " ) ;
}
2026-02-20 22:55:49 +01:00
}