Skip to content

Commit 615d34a

Browse files
authored
Preserve detached worker share credentials across restarts (anomalyco#1154)
1 parent 367e98c commit 615d34a

7 files changed

Lines changed: 120 additions & 22 deletions

File tree

‎apps/app/src/app/context/workspace.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1866,6 +1866,8 @@ export function createWorkspaceStore(options: {
18661866
const ok = await createRemoteWorkspaceFlow({
18671867
openworkHostUrl: host.openworkUrl,
18681868
openworkToken: host.ownerToken?.trim() || host.token,
1869+
openworkClientToken: host.token,
1870+
openworkHostToken: host.hostToken,
18691871
directory: resolvedFolder,
18701872
displayName: name,
18711873
sandboxBackend: host.sandboxBackend ?? "docker",
@@ -1913,6 +1915,8 @@ export function createWorkspaceStore(options: {
19131915
async function createRemoteWorkspaceFlow(input: {
19141916
openworkHostUrl?: string | null;
19151917
openworkToken?: string | null;
1918+
openworkClientToken?: string | null;
1919+
openworkHostToken?: string | null;
19161920
directory?: string | null;
19171921
displayName?: string | null;
19181922
manageBusy?: boolean;
@@ -2048,6 +2052,10 @@ export function createWorkspaceStore(options: {
20482052
remoteType,
20492053
openworkHostUrl: remoteType === "openwork" ? resolvedHostUrl : null,
20502054
openworkToken: remoteType === "openwork" ? (token || null) : null,
2055+
openworkClientToken:
2056+
remoteType === "openwork" ? (input.openworkClientToken?.trim() || null) : null,
2057+
openworkHostToken:
2058+
remoteType === "openwork" ? (input.openworkHostToken?.trim() || null) : null,
20512059
openworkWorkspaceId: remoteType === "openwork" ? openworkWorkspace?.id ?? null : null,
20522060
openworkWorkspaceName: remoteType === "openwork" ? openworkWorkspace?.name ?? null : null,
20532061
sandboxBackend: input.sandboxBackend ?? null,
@@ -2071,6 +2079,10 @@ export function createWorkspaceStore(options: {
20712079
displayName,
20722080
openworkHostUrl: remoteType === "openwork" ? resolvedHostUrl : null,
20732081
openworkToken: remoteType === "openwork" ? (token || null) : null,
2082+
openworkClientToken:
2083+
remoteType === "openwork" ? (input.openworkClientToken?.trim() || null) : null,
2084+
openworkHostToken:
2085+
remoteType === "openwork" ? (input.openworkHostToken?.trim() || null) : null,
20742086
openworkWorkspaceId: remoteType === "openwork" ? openworkWorkspace?.id ?? null : null,
20752087
openworkWorkspaceName: remoteType === "openwork" ? openworkWorkspace?.name ?? null : null,
20762088
sandboxBackend: input.sandboxBackend ?? null,
@@ -2132,6 +2144,8 @@ export function createWorkspaceStore(options: {
21322144
input: {
21332145
openworkHostUrl?: string | null;
21342146
openworkToken?: string | null;
2147+
openworkClientToken?: string | null;
2148+
openworkHostToken?: string | null;
21352149
directory?: string | null;
21362150
displayName?: string | null;
21372151
},
@@ -2241,6 +2255,10 @@ export function createWorkspaceStore(options: {
22412255
displayName,
22422256
openworkHostUrl: resolvedHostUrl,
22432257
openworkToken: token ? token : null,
2258+
openworkClientToken:
2259+
input.openworkClientToken?.trim() || workspace.openworkClientToken?.trim() || null,
2260+
openworkHostToken:
2261+
input.openworkHostToken?.trim() || workspace.openworkHostToken?.trim() || null,
22442262
openworkWorkspaceId: openworkWorkspace?.id ?? workspace.openworkWorkspaceId ?? null,
22452263
openworkWorkspaceName: openworkWorkspace?.name ?? workspace.openworkWorkspaceName ?? null,
22462264
});
@@ -2261,6 +2279,10 @@ export function createWorkspaceStore(options: {
22612279
displayName,
22622280
openworkHostUrl: resolvedHostUrl,
22632281
openworkToken: token ? token : null,
2282+
openworkClientToken:
2283+
input.openworkClientToken?.trim() || item.openworkClientToken?.trim() || null,
2284+
openworkHostToken:
2285+
input.openworkHostToken?.trim() || item.openworkHostToken?.trim() || null,
22642286
openworkWorkspaceId: openworkWorkspace?.id ?? item.openworkWorkspaceId ?? null,
22652287
openworkWorkspaceName: openworkWorkspace?.name ?? item.openworkWorkspaceName ?? null,
22662288
}
@@ -2397,7 +2419,11 @@ export function createWorkspaceStore(options: {
23972419
sandboxBackend: "docker",
23982420
runId: workspace.sandboxRunId?.trim() || null,
23992421
openworkToken:
2400-
workspace.openworkToken?.trim() || options.openworkServerSettings().token?.trim() || null,
2422+
workspace.openworkClientToken?.trim() ||
2423+
workspace.openworkToken?.trim() ||
2424+
options.openworkServerSettings().token?.trim() ||
2425+
null,
2426+
openworkHostToken: workspace.openworkHostToken?.trim() || null,
24012427
});
24022428

24032429
const resolved = await resolveOpenworkHost({
@@ -2417,6 +2443,8 @@ export function createWorkspaceStore(options: {
24172443
directory: resolved.directory || workspacePath,
24182444
openworkHostUrl: resolved.hostUrl,
24192445
openworkToken: host.ownerToken?.trim() || host.token,
2446+
openworkClientToken: host.token,
2447+
openworkHostToken: host.hostToken,
24202448
openworkWorkspaceId: resolved.workspace.id,
24212449
openworkWorkspaceName: resolved.workspace.name ?? workspace.openworkWorkspaceName ?? null,
24222450
sandboxBackend: host.sandboxBackend ?? "docker",

‎apps/app/src/app/lib/tauri.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ export type WorkspaceInfo = {
118118
displayName?: string | null;
119119
openworkHostUrl?: string | null;
120120
openworkToken?: string | null;
121+
openworkClientToken?: string | null;
122+
openworkHostToken?: string | null;
121123
openworkWorkspaceId?: string | null;
122124
openworkWorkspaceName?: string | null;
123125

@@ -187,6 +189,8 @@ export async function workspaceCreateRemote(input: {
187189
remoteType?: "openwork" | "opencode" | null;
188190
openworkHostUrl?: string | null;
189191
openworkToken?: string | null;
192+
openworkClientToken?: string | null;
193+
openworkHostToken?: string | null;
190194
openworkWorkspaceId?: string | null;
191195
openworkWorkspaceName?: string | null;
192196

@@ -202,6 +206,8 @@ export async function workspaceCreateRemote(input: {
202206
remoteType: input.remoteType ?? null,
203207
openworkHostUrl: input.openworkHostUrl ?? null,
204208
openworkToken: input.openworkToken ?? null,
209+
openworkClientToken: input.openworkClientToken ?? null,
210+
openworkHostToken: input.openworkHostToken ?? null,
205211
openworkWorkspaceId: input.openworkWorkspaceId ?? null,
206212
openworkWorkspaceName: input.openworkWorkspaceName ?? null,
207213
sandboxBackend: input.sandboxBackend ?? null,
@@ -218,6 +224,8 @@ export async function workspaceUpdateRemote(input: {
218224
remoteType?: "openwork" | "opencode" | null;
219225
openworkHostUrl?: string | null;
220226
openworkToken?: string | null;
227+
openworkClientToken?: string | null;
228+
openworkHostToken?: string | null;
221229
openworkWorkspaceId?: string | null;
222230
openworkWorkspaceName?: string | null;
223231

@@ -234,6 +242,8 @@ export async function workspaceUpdateRemote(input: {
234242
remoteType: input.remoteType ?? null,
235243
openworkHostUrl: input.openworkHostUrl ?? null,
236244
openworkToken: input.openworkToken ?? null,
245+
openworkClientToken: input.openworkClientToken ?? null,
246+
openworkHostToken: input.openworkHostToken ?? null,
237247
openworkWorkspaceId: input.openworkWorkspaceId ?? null,
238248
openworkWorkspaceName: input.openworkWorkspaceName ?? null,
239249
sandboxBackend: input.sandboxBackend ?? null,

‎apps/desktop/src-tauri/src/commands/engine.rs‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,7 @@ use crate::engine::manager::EngineManager;
99
use crate::engine::spawn::{find_free_port, spawn_engine};
1010
use crate::opencode_router::manager::OpenCodeRouterManager;
1111
use crate::opencode_router::spawn::resolve_opencode_router_health_port;
12-
use crate::openwork_server::{
13-
manager::OpenworkServerManager, start_openwork_server,
14-
};
12+
use crate::openwork_server::{manager::OpenworkServerManager, start_openwork_server};
1513
use crate::orchestrator::manager::OrchestratorManager;
1614
use crate::orchestrator::{self, OrchestratorSpawnOptions};
1715
use crate::types::{EngineDoctorResult, EngineInfo, EngineRuntime, ExecResult};
@@ -66,7 +64,10 @@ fn openwork_dev_mode_enabled() -> bool {
6664
}
6765

6866
fn pinned_opencode_version() -> String {
69-
let constants = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../constants.json"));
67+
let constants = include_str!(concat!(
68+
env!("CARGO_MANIFEST_DIR"),
69+
"/../../../constants.json"
70+
));
7071
let parsed: serde_json::Value =
7172
serde_json::from_str(constants).expect("constants.json must be valid JSON");
7273
parsed["opencodeVersion"]
@@ -396,8 +397,8 @@ pub fn engine_start(
396397
let notes_text = notes.join("\n");
397398
let install_command = pinned_opencode_install_command();
398399
return Err(format!(
399-
"OpenCode CLI not found.\n\nInstall with:\n- {install_command}\n\nNotes:\n{notes_text}"
400-
));
400+
"OpenCode CLI not found.\n\nInstall with:\n- {install_command}\n\nNotes:\n{notes_text}"
401+
));
401402
};
402403

403404
let (sidecar_candidate, _sidecar_notes) = resolve_sidecar_candidate(
@@ -713,8 +714,7 @@ pub fn engine_start(
713714
state.opencode_username = opencode_username.clone();
714715
state.opencode_password = opencode_password.clone();
715716

716-
let opencode_connect_url =
717-
format!("http://{client_host}:{port}");
717+
let opencode_connect_url = format!("http://{client_host}:{port}");
718718
let opencode_router_health_port = match resolve_opencode_router_health_port() {
719719
Ok(port) => Some(port),
720720
Err(error) => {

‎apps/desktop/src-tauri/src/commands/workspace.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,8 @@ pub fn workspace_create(
200200
display_name: None,
201201
openwork_host_url: None,
202202
openwork_token: None,
203+
openwork_client_token: None,
204+
openwork_host_token: None,
203205
openwork_workspace_id: None,
204206
openwork_workspace_name: None,
205207
sandbox_backend: None,
@@ -228,6 +230,8 @@ pub fn workspace_create_remote(
228230
remote_type: Option<RemoteType>,
229231
openwork_host_url: Option<String>,
230232
openwork_token: Option<String>,
233+
openwork_client_token: Option<String>,
234+
openwork_host_token: Option<String>,
231235
openwork_workspace_id: Option<String>,
232236
openwork_workspace_name: Option<String>,
233237
sandbox_backend: Option<String>,
@@ -260,6 +264,14 @@ pub fn workspace_create_remote(
260264
.map(|value| value.trim().to_string())
261265
.filter(|value| !value.is_empty());
262266

267+
let openwork_client_token = openwork_client_token
268+
.map(|value| value.trim().to_string())
269+
.filter(|value| !value.is_empty());
270+
271+
let openwork_host_token = openwork_host_token
272+
.map(|value| value.trim().to_string())
273+
.filter(|value| !value.is_empty());
274+
263275
if remote_type == RemoteType::Openwork {
264276
let host_url = openwork_host_url.clone().unwrap_or_default();
265277
if host_url.is_empty() {
@@ -307,6 +319,8 @@ pub fn workspace_create_remote(
307319
display_name,
308320
openwork_host_url,
309321
openwork_token,
322+
openwork_client_token,
323+
openwork_host_token,
310324
openwork_workspace_id,
311325
openwork_workspace_name,
312326
sandbox_backend: sandbox_backend
@@ -341,6 +355,8 @@ pub fn workspace_update_remote(
341355
remote_type: Option<RemoteType>,
342356
openwork_host_url: Option<String>,
343357
openwork_token: Option<String>,
358+
openwork_client_token: Option<String>,
359+
openwork_host_token: Option<String>,
344360
openwork_workspace_id: Option<String>,
345361
openwork_workspace_name: Option<String>,
346362
sandbox_backend: Option<String>,
@@ -410,6 +426,18 @@ pub fn workspace_update_remote(
410426
.filter(|value| !value.is_empty());
411427
}
412428

429+
if openwork_client_token.is_some() {
430+
entry.openwork_client_token = openwork_client_token
431+
.map(|value| value.trim().to_string())
432+
.filter(|value| !value.is_empty());
433+
}
434+
435+
if openwork_host_token.is_some() {
436+
entry.openwork_host_token = openwork_host_token
437+
.map(|value| value.trim().to_string())
438+
.filter(|value| !value.is_empty());
439+
}
440+
413441
if openwork_workspace_id.is_some() {
414442
entry.openwork_workspace_id = openwork_workspace_id
415443
.map(|value| value.trim().to_string())
@@ -899,6 +927,8 @@ pub fn workspace_import_config(
899927
display_name: None,
900928
openwork_host_url: None,
901929
openwork_token: None,
930+
openwork_client_token: None,
931+
openwork_host_token: None,
902932
openwork_workspace_id: None,
903933
openwork_workspace_name: None,
904934
sandbox_backend: None,

‎apps/desktop/src-tauri/src/lib.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,10 @@ pub fn run() {
244244
}
245245
#[cfg(target_os = "macos")]
246246
RunEvent::Opened { urls } => {
247-
let urls = urls.into_iter().map(|url| url.to_string()).collect::<Vec<_>>();
247+
let urls = urls
248+
.into_iter()
249+
.map(|url| url.to_string())
250+
.collect::<Vec<_>>();
248251
show_main_window(&app_handle);
249252
emit_native_deep_links(&app_handle, urls);
250253
}

‎apps/desktop/src-tauri/src/openwork_server/mod.rs‎

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,8 @@ fn save_openwork_server_token_store(
7878
fs::create_dir_all(parent)
7979
.map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
8080
}
81-
fs::write(
82-
path,
83-
serde_json::to_string_pretty(store).map_err(|e| e.to_string())?,
84-
)
85-
.map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
81+
let payload = serde_json::to_string_pretty(store).map_err(|e| e.to_string())?;
82+
fs::write(path, payload).map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
8683
Ok(())
8784
}
8885

@@ -98,13 +95,11 @@ fn load_or_create_workspace_tokens_at_path(
9895
path: &Path,
9996
workspace_key: &str,
10097
) -> Result<PersistedOpenworkServerTokens, String> {
101-
let mut store = load_openwork_server_token_store(&path)?;
98+
let mut store = load_openwork_server_token_store(path)?;
10299
if let Some(tokens) = store.workspaces.get(workspace_key) {
103100
return Ok(tokens.clone());
104101
}
105102

106-
// Keep the desktop-hosted share codes stable for the same workspace across
107-
// full app restarts so reconnecting clients do not need a fresh invite.
108103
let tokens = PersistedOpenworkServerTokens {
109104
client_token: generate_token(),
110105
host_token: generate_token(),
@@ -114,7 +109,7 @@ fn load_or_create_workspace_tokens_at_path(
114109
store
115110
.workspaces
116111
.insert(workspace_key.to_string(), tokens.clone());
117-
save_openwork_server_token_store(&path, &store)?;
112+
save_openwork_server_token_store(path, &store)?;
118113
Ok(tokens)
119114
}
120115

@@ -132,13 +127,13 @@ fn persist_workspace_owner_token_at_path(
132127
workspace_key: &str,
133128
owner_token: &str,
134129
) -> Result<(), String> {
135-
let mut store = load_openwork_server_token_store(&path)?;
130+
let mut store = load_openwork_server_token_store(path)?;
136131
let Some(tokens) = store.workspaces.get_mut(workspace_key) else {
137132
return Ok(());
138133
};
139134
tokens.owner_token = Some(owner_token.to_string());
140135
tokens.updated_at = now_ms();
141-
save_openwork_server_token_store(&path, &store)
136+
save_openwork_server_token_store(path, &store)
142137
}
143138

144139
fn wait_for_openwork_health(base_url: &str, timeout: Duration) -> Result<(), String> {
@@ -192,7 +187,6 @@ fn build_urls(port: u16) -> (Option<String>, Option<String>, Option<String>) {
192187
};
193188

194189
let lan_url = local_ip().ok().map(|ip| format!("http://{ip}:{port}"));
195-
196190
let connect_url = lan_url.clone().or(mdns_url.clone());
197191

198192
(connect_url, mdns_url, lan_url)
@@ -323,3 +317,32 @@ pub fn start_openwork_server(
323317

324318
Ok(OpenworkServerManager::snapshot_locked(&mut state))
325319
}
320+
321+
#[cfg(test)]
322+
mod tests {
323+
use super::*;
324+
use std::time::{SystemTime, UNIX_EPOCH};
325+
326+
fn unique_temp_path(name: &str) -> PathBuf {
327+
let nonce = SystemTime::now()
328+
.duration_since(UNIX_EPOCH)
329+
.expect("clock before unix epoch")
330+
.as_nanos();
331+
std::env::temp_dir().join(format!("openwork-server-{name}-{nonce}.json"))
332+
}
333+
334+
#[test]
335+
fn reuses_tokens_for_the_same_workspace_after_restart() {
336+
let path = unique_temp_path("reuse");
337+
let first = load_or_create_workspace_tokens_at_path(&path, "/tmp/workspace")
338+
.expect("create first token set");
339+
let second = load_or_create_workspace_tokens_at_path(&path, "/tmp/workspace")
340+
.expect("load existing token set");
341+
342+
assert_eq!(first.client_token, second.client_token);
343+
assert_eq!(first.host_token, second.host_token);
344+
assert_eq!(first.owner_token, second.owner_token);
345+
346+
let _ = fs::remove_file(path);
347+
}
348+
}

‎apps/desktop/src-tauri/src/types.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,10 @@ pub struct WorkspaceInfo {
327327
#[serde(default)]
328328
pub openwork_token: Option<String>,
329329
#[serde(default)]
330+
pub openwork_client_token: Option<String>,
331+
#[serde(default)]
332+
pub openwork_host_token: Option<String>,
333+
#[serde(default)]
330334
pub openwork_workspace_id: Option<String>,
331335
#[serde(default)]
332336
pub openwork_workspace_name: Option<String>,

0 commit comments

Comments
 (0)