From da68755d4faa103b1ddf285622b1479d024175cd Mon Sep 17 00:00:00 2001 From: wang2 <134143178+fatwang2@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:50:33 +0800 Subject: [PATCH 1/3] fix: make onboarding local-first and desktop imports opt-in --- CHANGELOG.md | 6 + desktop/crates/bar-core/src/settings.rs | 26 ++++ desktop/src-tauri/src/main.rs | 187 ++++++++++++++++++++++-- desktop/src/App.tsx | 20 ++- desktop/src/app-preview.test.tsx | 56 ++++++- desktop/src/contracts.ts | 2 +- desktop/src/style.css | 2 + docs/COMPATIBILITY.md | 7 +- docs/USAGE.md | 6 +- 9 files changed, 290 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cb0685..653b194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ This log records user-visible changes. GitHub releases contain package downloads ## Unreleased +### Changed + +- Start onboarding with local pairing instructions and put the local connection first in Settings. +- Make importing T3 Code's encrypted environment catalog opt-in; preserve Bar's own pairing credentials and independent manual and T3 Connect connections. +- Distinguish a running local server from an authorized Bar connection instead of showing unpaired installations as connected. + ### Maintenance - Add contribution, security, support, community, and issue-reporting guidance. diff --git a/desktop/crates/bar-core/src/settings.rs b/desktop/crates/bar-core/src/settings.rs index 7ac71b8..4243f19 100644 --- a/desktop/crates/bar-core/src/settings.rs +++ b/desktop/crates/bar-core/src/settings.rs @@ -6,6 +6,7 @@ use std::{fs, io, path::PathBuf}; #[serde(rename_all = "camelCase", default)] pub struct Settings { pub environment_selection: EnvironmentSelection, + pub imports_desktop_environments: bool, pub notifications_muted: bool, pub shows_previews: bool, pub automatically_checks_for_updates: bool, @@ -15,6 +16,7 @@ impl Default for Settings { fn default() -> Self { Self { environment_selection: EnvironmentSelection::All, + imports_desktop_environments: false, notifications_muted: false, shows_previews: true, automatically_checks_for_updates: true, @@ -26,6 +28,7 @@ impl Default for Settings { #[derive(Clone, Copy, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub enum SettingKey { + ImportsDesktopEnvironments, NotificationsMuted, ShowsPreviews, AutomaticallyChecksForUpdates, @@ -73,6 +76,7 @@ impl SettingsStore { pub fn set(&mut self, key: SettingKey, enabled: bool) -> io::Result<()> { let mut next = self.value.clone(); match key { + SettingKey::ImportsDesktopEnvironments => next.imports_desktop_environments = enabled, SettingKey::NotificationsMuted => next.notifications_muted = enabled, SettingKey::ShowsPreviews => next.shows_previews = enabled, SettingKey::AutomaticallyChecksForUpdates => { @@ -150,12 +154,34 @@ mod tests { let mut store = SettingsStore::load(path.clone()).unwrap(); assert!(store.value().notifications_muted); assert!(store.value().shows_previews); + assert!(!store.value().imports_desktop_environments); store.set(SettingKey::ShowsPreviews, false).unwrap(); let read = SettingsStore::load(path).unwrap(); assert!(!read.value().shows_previews); assert!(read.value().notifications_muted); } #[test] + fn desktop_environment_import_is_opt_in_and_survives_restart() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let mut store = SettingsStore::load(path.clone()).unwrap(); + assert!(!store.value().imports_desktop_environments); + store + .set(SettingKey::ImportsDesktopEnvironments, true) + .unwrap(); + let mut restored = SettingsStore::load(path.clone()).unwrap(); + assert!(restored.value().imports_desktop_environments); + restored + .set(SettingKey::ImportsDesktopEnvironments, false) + .unwrap(); + assert!( + !SettingsStore::load(path) + .unwrap() + .value() + .imports_desktop_environments + ); + } + #[test] fn selection_defaults_and_survives_restart_with_other_preferences() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("settings.json"); diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index bb13801..448f86c 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -501,7 +501,11 @@ fn connection_for(state: &RuntimeState, online: bool, has_data: bool) -> Connect limits::LiveStatus::Failed(message) => ("failed", message.clone()), _ if !online => ( "offline", - "Open T3 Code to connect. Showing saved data when present.".to_owned(), + "Open T3 Code on this computer, then enter a pairing key to connect.".to_owned(), + ), + _ if !live.has_credential => ( + "unpaired", + "T3 Code is running. Pair to give Bar read access.".to_owned(), ), _ => ( "cacheOnly", @@ -544,7 +548,8 @@ fn view_snapshot(state: &RuntimeState) -> Result { .lock() .map_err(|_| "snapshot unavailable")? .clone(); - snapshot.local_connection = connection_for(state, false, snapshot.connection.has_data); + let local_online = state.config.is_server_online(); + snapshot.local_connection = connection_for(state, local_online, snapshot.connection.has_data); snapshot.cloud_status = match state.cloud.as_ref().and_then(|c| c.status().ok()) { Some(LoginStatus::SignedOut) => "signedOut", Some(LoginStatus::SigningIn) => "signingIn", @@ -583,6 +588,9 @@ fn view_snapshot(state: &RuntimeState) -> Result { } else if local_id.as_ref() == Some(&source.metadata.id) && matches!(snapshot.local_connection.status.as_str(), "restoring" | "credentialUnavailable") { snapshot.local_connection.status.as_str() + } else if local_id.as_ref() == Some(&source.metadata.id) + && !snapshot.local_connection.paired { + if local_online { "needsAccess" } else { "offline" } } else if source.attempt_status.is_some() { match source.attempt_status.as_ref().unwrap() { AttemptStatus::Offline => "offline", @@ -638,15 +646,23 @@ fn view_snapshot(state: &RuntimeState) -> Result { .any(|source| !local_sources.contains_key(&source.metadata.id) && source.stamp.is_some()); snapshot.online = selected_online; if !selected_views.is_empty() { - snapshot.connection.paired = selected_access - || (snapshot.connection.paired - && local_environment(&state.config) - .ok() - .is_some_and(|id| selected(hub.selection(), &id))); - snapshot.connection.connected = selected_online; - if selected_online { + let local_selected = local_id + .as_ref() + .is_some_and(|id| selected(hub.selection(), id)); + snapshot.connection.paired = + selected_access || (snapshot.local_connection.paired && local_selected); + snapshot.connection.connected = selected_views.iter().any(|environment| { + if environment.is_local { + snapshot.local_connection.connected + } else { + environment.status == "online" + } + }); + if snapshot.connection.connected { snapshot.connection.status = "connected".into(); snapshot.connection.message = "Connected to selected environments".into(); + } else if !snapshot.connection.paired && local_selected { + snapshot.connection = snapshot.local_connection.clone(); } else if selected_views .iter() .any(|entry| entry.status == "restoring") @@ -929,6 +945,12 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { } let mut paths = HashMap::new(); paths.insert(local.clone(), state.config.clone()); + let imports_desktop_environments = state + .hub + .lock() + .map_err(|_| "settings unavailable")? + .settings() + .imports_desktop_environments; let entries = if state.fixture { if let Some(path) = fixture_or_env("T3_BAR_FIXTURE_ENVIRONMENTS") { let entries = serde_json::from_slice::( @@ -971,12 +993,14 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { } else { Ok(vec![primary.clone()]) } - } else { + } else if imports_desktop_environments { bar_core::connection::catalog::discover( &state.config.base_dir.join("connection-catalog.json"), primary.clone(), ) .map_err(|_| ()) + } else { + Ok(vec![primary.clone()]) }; let directory = state.cloud_directory.lock().ok() .filter(|cache| cache.generation == state.cloud_generation.load(std::sync::atomic::Ordering::Acquire)) @@ -4142,6 +4166,149 @@ while True: tokio::runtime::Runtime::new().unwrap() } + #[test] + fn local_server_discovery_does_not_claim_a_pairing_or_connection() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("environment-id"), "local-env").unwrap(); + std::fs::write( + directory.path().join("server-runtime.json"), + json!({ + "pid": std::process::id(), "port": 43101 + }) + .to_string(), + ) + .unwrap(); + let state = ssh_state(directory.path(), Default::default()); + discover_sources(&state).unwrap(); + let local = EnvironmentId::new("local-env").unwrap(); + list_threads(&state, &local, &["saved-thread"]); + let snapshot = view_snapshot(&state).unwrap(); + assert!(!snapshot.local_connection.paired); + assert!(!snapshot.local_connection.connected); + assert_eq!(snapshot.local_connection.status, "unpaired"); + assert!(snapshot + .local_connection + .message + .contains("T3 Code is running")); + assert!(!snapshot.connection.paired); + assert!(!snapshot.connection.connected); + assert_eq!(snapshot.connection.status, "unpaired"); + assert_eq!(snapshot.environments[0].status, "needsAccess"); + } + + #[test] + fn desktop_catalog_is_not_read_without_explicit_opt_in() { + use bar_core::environments::DiscoveryState; + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("environment-id"), "local-env").unwrap(); + let catalog = directory.path().join("connection-catalog.json"); + std::fs::create_dir(&catalog).unwrap(); + let mut state = ssh_state(directory.path(), Default::default()); + Arc::get_mut(&mut state).unwrap().fixture = false; + discover_sources(&state).unwrap(); + assert_eq!( + state.hub.lock().unwrap().discovery_state(), + &DiscoveryState::Ready + ); + assert_eq!(state.hub.lock().unwrap().sources().len(), 1); + + state.catalog_metadata.lock().unwrap().clear(); + state + .hub + .lock() + .unwrap() + .set_setting(SettingKey::ImportsDesktopEnvironments, true) + .unwrap(); + discover_sources(&state).unwrap(); + assert_eq!( + state.hub.lock().unwrap().discovery_state(), + &DiscoveryState::Stale + ); + assert_eq!(state.hub.lock().unwrap().sources().len(), 1); + + state + .hub + .lock() + .unwrap() + .set_setting(SettingKey::ImportsDesktopEnvironments, false) + .unwrap(); + discover_sources(&state).unwrap(); + assert_eq!( + state.hub.lock().unwrap().discovery_state(), + &DiscoveryState::Ready + ); + assert!(catalog.is_dir()); + } + + #[test] + fn manual_and_cloud_routes_do_not_require_desktop_catalog_import() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("environment-id"), "local-env").unwrap(); + let manual = EnvironmentMetadata { + id: EnvironmentId::new("manual-env").unwrap(), + label: "Manual".into(), + enabled: true, + routes: vec![Route::Bearer { + connection_id: "bar-manual".into(), + http_base_url: Some("https://manual.example/".into()), + }], + }; + let connection_file = directory.path().join("connections.json"); + let saved = serde_json::to_vec(&json!({ "version": 1, "environments": [manual] })).unwrap(); + std::fs::write(&connection_file, &saved).unwrap(); + let mut state = ssh_state(directory.path(), Default::default()); + Arc::get_mut(&mut state).unwrap().fixture = false; + state + .cloud_directory + .lock() + .unwrap() + .entries + .push(EnvironmentMetadata { + id: EnvironmentId::new("cloud-env").unwrap(), + label: "Cloud".into(), + enabled: true, + routes: vec![Route::Bearer { + connection_id: "cloud-directory".into(), + http_base_url: Some("https://cloud.example/".into()), + }], + }); + let _gate = state.manual_connection_gate.lock().unwrap(); + discover_sources_locked(&state).unwrap(); + assert!( + !state + .hub + .lock() + .unwrap() + .settings() + .imports_desktop_environments + ); + assert_eq!(state.hub.lock().unwrap().sources().len(), 3); + let routes = state.remote_routes.lock().unwrap(); + assert!(routes.contains_key(&EnvironmentId::new("manual-env").unwrap())); + assert!(routes.contains_key(&EnvironmentId::new("cloud-env").unwrap())); + assert_eq!(std::fs::read(connection_file).unwrap(), saved); + } + + #[test] + fn saved_local_pairing_remains_available_without_catalog_import_or_a_running_server() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("environment-id"), "local-env").unwrap(); + let mut state = ssh_state(directory.path(), Default::default()); + Arc::get_mut(&mut state).unwrap().connection = + limits::LimitsConnection::with_default_transport(Arc::new(FixtureCredentials( + Mutex::new(Some( + limits::Credential::new(43101, "synthetic-credential").unwrap(), + )), + ))); + state.connection.restore_saved().unwrap(); + discover_sources(&state).unwrap(); + let snapshot = view_snapshot(&state).unwrap(); + assert!(snapshot.local_connection.paired); + assert!(snapshot.connection.paired); + assert!(!snapshot.connection.connected); + assert!(!snapshot.settings.imports_desktop_environments); + } + fn grant_with( state: &RuntimeState, runtime: &tokio::runtime::Runtime, diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index a23da58..10f2d6e 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -90,14 +90,14 @@ export function App() { return () => window.removeEventListener('keydown', key); }, [screen, context, act]); - const hasThreadAccess = snapshot !== null && (snapshot.connection.paired || snapshot.environments.some(environment => + const hasThreadAccess = snapshot !== null && (snapshot.localConnection.paired || snapshot.connection.paired || snapshot.environments.some(environment => !environment.isLocal && (environment.status === 'online' || snapshot.threads.some(thread => thread.thread.environmentId === environment.id)))); return
setContext(null)}> {error &&
{error}
} {!snapshot ? : screen === 'settings' ? <>
Settings
- : !hasThreadAccess ?

Connect T3 Code

+ : !hasThreadAccess ?

Connect this computer

Pair with T3 Code on this computer to see your threads, replies and usage. Remote environments and T3 Connect sign-in are optional in Settings.
: screen === 'threads' ? <>
@@ -144,15 +144,20 @@ function SettingsPage({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) { }; const toggle = (label: string, key: Exclude, checked: boolean, disabled = false, invert = false) => ; return
-

Environment

{snapshot.environments.map(environment => )}
+

Local T3 Code connection

Pairing here connects Bar to this computer. Add other machines separately below. + {snapshot.localConnection.paired && (confirmDisconnect ?

Disconnect and remove the saved pairing key? You will need a new key to connect again.

: )} +
+

Environment

+ Optional: import saved environments instead of adding their addresses manually. This may ask to read T3 Code’s encrypted connection list using its Keychain or Secret Service entry. Importing only discovers environments; each still needs its own Bar pairing. + {toggle('Import environments from T3 Code', 'importsDesktopEnvironments', snapshot.settings.importsDesktopEnvironments)} + Turning import off stops discovery from that list. Your saved Bar pairing credentials are not deleted. Local pairing, manually added environments and T3 Connect work without this import. + {snapshot.environments.map(environment => )} +

T3 Connect

Sign in to find linked environments. Pair once with each environment to read through its public HTTPS tunnel. Tailscale is not required.{snapshot.cloudError && {snapshot.cloudError}}{snapshot.cloudStatus === 'signedOut' && }{snapshot.cloudStatus === 'signingIn' && }{snapshot.cloudStatus === 'signedIn' && }{snapshot.cloudStatus === 'recoveryRequired' && <>Saved T3 Connect credentials need recovery. Restore access to your system keyring, then retry sign out. Some saved credentials may remain until cleanup succeeds.}{snapshot.cloudStatus === 'unavailable' && T3 Connect unavailable}

Preferences

{toggle('Notifications', 'notificationsMuted', !snapshot.settings.notificationsMuted, false, true)} {toggle('Hover previews', 'showsPreviews', snapshot.settings.showsPreviews)}
-

Local T3 Code connection

Pairing here connects Bar to T3 Code on this machine. For another machine, use its named pairing field above. - {snapshot.localConnection.paired && (confirmDisconnect ?

Disconnect and remove the saved pairing key? You will need a new key to connect again.

: )} -

Updates

{toggle('Check automatically', 'automaticallyChecksForUpdates', snapshot.settings.automaticallyChecksForUpdates, unavailable || updateBusy)} {toggle('Install without asking', 'installsWithoutAsking', snapshot.settings.installsWithoutAsking, unavailable || updateBusy || !snapshot.settings.automaticallyChecksForUpdates)} @@ -269,7 +274,8 @@ function Connection({ snapshot, act, compact: minimal = false, local = false }: {!storageUnavailable && !restoring && connection.paired &&
} {!storageUnavailable && !restoring && !connection.paired && minimal && } {!storageUnavailable && !restoring && expanded &&
{ e.preventDefault(); if (token.trim() && !busy) void connect('connect'); }}> - setToken(e.target.value)} /> + {local &&
  1. In T3 Code, open Settings → Sharing & access.
  2. Under Authorized clients, choose Create link with read-only permissions.
  3. Copy the one-time pairing code and paste it below.

Bar saves its own pairing credential in your OS credential store for reconnects. Local pairing does not need access to T3 Code’s saved environment key.

} + setToken(e.target.value)} />
} } diff --git a/desktop/src/app-preview.test.tsx b/desktop/src/app-preview.test.tsx index f857a14..1f1857e 100644 --- a/desktop/src/app-preview.test.tsx +++ b/desktop/src/app-preview.test.tsx @@ -32,7 +32,7 @@ const snapshot = (showsPreviews: boolean): AppSnapshot => ({ localConnection: { status: 'connected', message: 'Connected', connected: true, paired: true, hasData: true, port: 0, updatedAt: null }, connection: { status: 'connected', message: 'Connected', connected: true, paired: true, hasData: true, port: 0, updatedAt: null }, usage: null, usageError: null, usageLoading: false, usagePeriod: '24h', limits: null, - settings: { environmentSelection: 'all', notificationsMuted: false, showsPreviews, automaticallyChecksForUpdates: false, installsWithoutAsking: false }, + settings: { environmentSelection: 'all', importsDesktopEnvironments: false, notificationsMuted: false, showsPreviews, automaticallyChecksForUpdates: false, installsWithoutAsking: false }, update: { status: 'idle', message: '', version: null, offerId: null, canInstall: false, busy: false }, version: 'test', }); @@ -188,6 +188,39 @@ describe('thread preview lifecycle', () => { }); describe('new-install pairing', () => { + it('uses local pairing state even when discovery reports an aggregate connection', async () => { + const value = snapshot(true); + value.connection = { ...value.connection, connected: true, paired: false }; + value.localConnection = { ...value.connection, connected: false, status: 'unpaired', message: 'T3 Code is running. Pair to give Bar read access.' }; + value.environments = [{ id: 'local', label: 'Local', machine: 'laptop', status: 'online', access: 'direct', isLocal: true, canForgetAccess: false }]; + await renderSnapshot(value); + expect(host.querySelector('.onboarding')).not.toBeNull(); + expect(host.textContent).toContain('Connect this computer'); + expect(host.textContent).toContain('Settings → Sharing & access'); + expect(host.textContent).toContain('Authorized clients'); + expect(host.textContent).toContain('Create link'); + expect(host.textContent).not.toContain('Connected to T3 Code'); + const input = host.querySelector('input[type="password"]'); + expect(input?.getAttribute('aria-describedby')).toBe('local-pairing-help'); + expect(host.querySelectorAll('form')).toHaveLength(1); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'begin_cloud_login')).toBe(false); + expect(tauri.invoke).not.toHaveBeenCalledWith('set_setting', expect.anything()); + }); + + it('keeps a paired local installation out of onboarding when an unpaired remote is selected', async () => { + const value = snapshot(true); + value.connection = { ...value.connection, connected: false, paired: false }; + value.settings.environmentSelection = { one: 'remote' }; + value.environments = [ + { id: 'local', label: 'Local', machine: 'laptop', status: 'online', access: 'direct', isLocal: true, canForgetAccess: false }, + { id: 'remote', label: 'Remote', machine: 'server', status: 'needsAccess', access: 'direct', isLocal: false, canForgetAccess: false }, + ]; + value.threads = []; + await renderSnapshot(value); + expect(host.querySelector('.onboarding')).toBeNull(); + expect(host.querySelector('[aria-label="Environment selector"]')).not.toBeNull(); + }); + it('requires a pairing key even when T3 Code already has cached data', async () => { const value = snapshot(true); value.connection = { ...value.connection, connected: false, paired: false, status: 'cacheOnly' }; @@ -230,6 +263,23 @@ describe('new-install pairing', () => { }); describe('settings state and actions', () => { + it('puts local pairing before remote settings and enables desktop imports only on request', async () => { + await openSettings(); + expect(host.querySelector('.settings section h2')?.textContent).toBe('Local T3 Code connection'); + const importToggle = [...host.querySelectorAll('label')].find(label => label.textContent === 'Import environments from T3 Code')!.querySelector('input')!; + expect(importToggle.checked).toBe(false); + expect(host.textContent).toContain('each still needs its own Bar pairing'); + expect(tauri.invoke).not.toHaveBeenCalledWith('set_setting', expect.anything()); + await act(async () => importToggle.click()); + expect(tauri.invoke).toHaveBeenCalledWith('set_setting', { key: 'importsDesktopEnvironments', value: true }); + act(() => tauri.listeners.get('bar-snapshot')?.({ payload: { ...snapshot(true), settings: { ...snapshot(true).settings, importsDesktopEnvironments: true } } })); + expect(importToggle.checked).toBe(true); + await act(async () => importToggle.click()); + expect(tauri.invoke).toHaveBeenLastCalledWith('set_setting', { key: 'importsDesktopEnvironments', value: false }); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'disconnect')).toBe(false); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'forget_environment_access')).toBe(false); + }); + it('keeps an environment form and its failure visible when the panel reopens', async () => { await openSettings(); act(() => button('Add environment').click()); @@ -311,7 +361,9 @@ describe('settings state and actions', () => { await openSettings(value); expect(button('Check for Updates…').disabled).toBe(true); expect(host.textContent).toContain('Updates unavailable in this build'); - expect([...host.querySelectorAll('[role="switch"]')].slice(2).every(input => input.disabled)).toBe(true); + const updateSwitches = host.querySelectorAll('.settings section:last-of-type [role="switch"]'); + expect(updateSwitches).toHaveLength(2); + expect([...updateSwitches].every(input => input.disabled)).toBe(true); }); }); diff --git a/desktop/src/contracts.ts b/desktop/src/contracts.ts index ec07b26..68f8cd2 100644 --- a/desktop/src/contracts.ts +++ b/desktop/src/contracts.ts @@ -59,7 +59,7 @@ export interface LimitRow { id: string; label: string; remainingPercent: number; export interface LimitGroup { driver: string; label: string; rows: LimitRow[] } export interface LimitsReport { groups: LimitGroup[]; notices: string[]; checkedAt: string | null; readFailed?: boolean; skippedFiles?: number; links: { label: string; url: string; message?: string | null; accounts?: string[] }[] } export interface ConnectionState { status: string; message: string; connected: boolean; paired: boolean; hasData: boolean; port: number; updatedAt: string | null } -export interface Settings { environmentSelection: EnvironmentSelection; notificationsMuted: boolean; showsPreviews: boolean; automaticallyChecksForUpdates: boolean; installsWithoutAsking: boolean } +export interface Settings { environmentSelection: EnvironmentSelection; importsDesktopEnvironments: boolean; notificationsMuted: boolean; showsPreviews: boolean; automaticallyChecksForUpdates: boolean; installsWithoutAsking: boolean } export interface UpdateState { status: string; message: string; version: string | null; offerId: number | null; canInstall: boolean; busy: boolean } export interface AppSnapshot { revision: number; diff --git a/desktop/src/style.css b/desktop/src/style.css index de55f33..0176033 100644 --- a/desktop/src/style.css +++ b/desktop/src/style.css @@ -95,6 +95,8 @@ h2 small { font-size: var(--bar-font-10, 10px); margin-left: auto; color: #8b8b9 .empty { padding: 24px 10px; text-align: center; color: #a1a1aa; font-size: var(--bar-font-12, 12px); }.empty strong { font-weight: 500; }.empty p { color: #8b8b94; font-size: var(--bar-font-11, 11px); line-height: var(--bar-font-17, 17px); margin-bottom: 0; } .stale { opacity: .45; }.onboarding { padding: 16px; }.onboarding h1 { margin-bottom: 12px; } .connection input { width: 100%; }.connection form { display: flex; flex-direction: column; gap: 8px; }.connection-actions { display: flex; gap: 6px; }.connection-actions button { font-size: var(--bar-font-10, 10px); padding: 6px; }.connection-actions button:last-child { flex: 1; } +.pairing-help { color: var(--linux-muted, #a3a3a3); font-size: var(--bar-font-11, 11px); line-height: var(--bar-font-17, 17px); } +.pairing-help ol { margin: 0; padding-left: 18px; }.pairing-help li + li { margin-top: 4px; }.pairing-help p { margin: 8px 0 0; } .text-button { border: 0; padding: 0; color: #a5b4fc; background: none; text-align: left; }.text-button:hover { background: none; color: #d0d6ff; }.subtle { color: #a1a1aa; margin-top: 12px; } .settings { padding: 0 16px 14px; max-height: 516px; }.version { color: #8b8b94; margin-left: auto; font-size: var(--bar-font-10, 10px); }.toggle { display: flex; align-items: center; justify-content: space-between; gap: 14px; min-height: 38px; font-size: var(--bar-font-11_5, 11.5px); line-height: var(--bar-font-16, 16px); }.settings section { padding: 14px 0; margin: 0; border-top: 1px solid #191919; } .settings section:first-child { border-top: 0; padding-top: 4px; } diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index 7009aea..b9769eb 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -24,7 +24,12 @@ environment show that icon; the current local environment has no machine icon. The Bar shows the main sidebar list, excluding settled, snoozed, archived, deleted, delegated and side-chat threads from both local and remote sources. -Linux and macOS discovery project the installed T3 desktop connection catalog. +Linux and macOS discovery can project the installed T3 desktop connection catalog +when **Import environments from T3 Code** is enabled in Settings. It is disabled +by default, including for settings written before the preference existed. Local +pairing, manual routes and T3 Connect discovery do not require this import. +Disabling it preserves saved Bar grants; catalog-only routes require opting in +again or adding an independent manual route to reconnect. Discovery provides metadata and routes; it does not authorize reads. Bar pairs with its own read grant for direct, public HTTPS tunnel and SSH routes. T3 Connect sign-in uses Bar's OAuth token to list linked environments and their public tunnel diff --git a/docs/USAGE.md b/docs/USAGE.md index 3045d98..7fefa6f 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1,6 +1,10 @@ # Usage -Start T3 Code, then launch the Bar. Enter a pairing key from T3 Code to connect. The key is saved in the Bar's own OS credential namespace for later reconnects. +Start T3 Code, then launch the Bar. In T3 Code, open **Settings → Sharing & access → Authorized clients → Create link** and choose read-only permissions. Copy its one-time pairing code into **Local pairing key** in the Bar, then click **Connect**. The Bar saves its own pairing credential in its OS credential namespace for later reconnects. OS permission approval and discovering a running T3 Code server do not complete pairing. + +Local setup does not require T3 Connect sign-in or access to T3 Code's saved environment key. Settings puts **Local T3 Code connection** first. Add a remote environment manually by address or SSH host, or sign in to T3 Connect to find linked environments. + +**Import environments from T3 Code** in Settings is optional and off by default, including after upgrading from a version without this preference. Turn it on only if you want the Bar to discover T3 Code's saved connections. Reading that encrypted list may require approval for T3 Code's Keychain or Secret Service entry; it discovers metadata and routes, not read authorization. Pair separately with each environment. Turning import off stops catalog discovery without deleting Bar's saved credentials. Imported-only environments may become unavailable until you turn import back on or add their route manually. Manual connections and T3 Connect discovery are independent of this preference. ## Threads and usage From d23eafeabec8991190619742236985bbb02f7a22 Mon Sep 17 00:00:00 2001 From: wang2 <134143178+fatwang2@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:27:15 +0800 Subject: [PATCH 2/3] fix: simplify pairing and isolate local connection settings --- CHANGELOG.md | 4 +- desktop/crates/bar-limits/src/live.rs | 76 +++++++++++++++- desktop/crates/bar-limits/src/live_tests.rs | 85 ++++++++++++++++-- desktop/src-tauri/src/main.rs | 16 ++++ desktop/src/App.tsx | 39 +++++---- desktop/src/app-preview.test.tsx | 96 ++++++++++++++++++++- docs/USAGE.md | 8 +- 7 files changed, 294 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 653b194..47f535b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,9 @@ This log records user-visible changes. GitHub releases contain package downloads ### Changed -- Start onboarding with local pairing instructions and put the local connection first in Settings. +- Start onboarding with local pairing instructions and a single connection action. Settings shows a compact local status with a separate Manage connection page. +- Exclude Local from remote pairing controls so an unpaired local server cannot submit through the remote-only pairing command. +- Accept complete local pairing links and add an explicit Paste and connect action; reject links for other destinations before exchanging the code. - Make importing T3 Code's encrypted environment catalog opt-in; preserve Bar's own pairing credentials and independent manual and T3 Connect connections. - Distinguish a running local server from an authorized Bar connection instead of showing unpaired installations as connected. diff --git a/desktop/crates/bar-limits/src/live.rs b/desktop/crates/bar-limits/src/live.rs index b9a281d..3d7651c 100644 --- a/desktop/crates/bar-limits/src/live.rs +++ b/desktop/crates/bar-limits/src/live.rs @@ -36,10 +36,80 @@ fn is_pairing_code(token: &str) -> bool { .all(|c| PAIRING_ALPHABET.contains(c.to_ascii_uppercase())) } +fn local_pairing_input(port: u16, input: &str) -> Result { + Credential::new(port, input)?.validate()?; + let input = input.trim(); + if !input.contains("://") + && !input.starts_with("http:") + && !input.starts_with("https:") + && !input.starts_with("t3code:") + { + return Ok(input.to_owned()); + } + let mut url = url::Url::parse(input).map_err(|_| ConnectionError::InvalidPairingLink)?; + if url.scheme() == "t3code" { + if url.host_str() != Some("pair") + || !url.username().is_empty() + || url.password().is_some() + || url.port().is_some() + || !matches!(url.path(), "" | "/") + || url.fragment().is_some() + { + return Err(ConnectionError::InvalidPairingLink); + } + let fields: Vec<_> = url.query_pairs().collect(); + if fields.len() != 1 || fields[0].0 != "pairingUrl" { + return Err(ConnectionError::InvalidPairingLink); + } + url = url::Url::parse(&fields[0].1).map_err(|_| ConnectionError::InvalidPairingLink)?; + } + if url.scheme() == "https" && url.host_str() == Some("app.t3.codes") && url.path() == "/pair" { + if !url.username().is_empty() || url.password().is_some() || url.port().is_some() { + return Err(ConnectionError::InvalidPairingLink); + } + let fields: Vec<_> = url.query_pairs().collect(); + if fields.len() != 1 || fields[0].0 != "host" { + return Err(ConnectionError::InvalidPairingLink); + } + let mut destination = + url::Url::parse(&fields[0].1).map_err(|_| ConnectionError::InvalidPairingLink)?; + if !matches!(destination.path(), "" | "/") + || destination.query().is_some() + || destination.fragment().is_some() + { + return Err(ConnectionError::InvalidPairingLink); + } + destination.set_path("/pair"); + destination.set_fragment(url.fragment()); + url = destination; + } + if url.scheme() != "http" + || !matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")) + || url.port_or_known_default() != Some(port) + { + return Err(ConnectionError::PairingDestination); + } + if !url.username().is_empty() + || url.password().is_some() + || url.path() != "/pair" + || url.query().is_some() + { + return Err(ConnectionError::InvalidPairingLink); + } + let fields: Vec<_> = + url::form_urlencoded::parse(url.fragment().unwrap_or_default().as_bytes()).collect(); + if fields.len() != 1 || fields[0].0 != "token" || !is_pairing_code(&fields[0].1) { + return Err(ConnectionError::InvalidPairingLink); + } + Ok(fields[0].1.to_ascii_uppercase()) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ConnectionError { Destination, InvalidToken, + InvalidPairingLink, + PairingDestination, Authorization, PairingRejected, Expired, @@ -53,6 +123,8 @@ impl fmt::Display for ConnectionError { f.write_str(match self { Self::Destination => "Enter a local T3 Code port from 1 to 65535.", Self::InvalidToken => "Enter a T3 Code access token of up to 16 KiB.", + Self::InvalidPairingLink => "This pairing link is incomplete or invalid. Copy a fresh link from T3 Code, or use Copy code only.", + Self::PairingDestination => "This link does not match the running local T3 Code server. Create a link for this computer, or use Add environment for another machine. No pairing code was sent.", Self::Authorization => "The access token was rejected by T3 Code.", Self::PairingRejected => "T3 Code rejected this pairing key. It may have expired or already been used. Create a new pairing key and try again.", Self::Expired => { @@ -478,10 +550,10 @@ impl LimitsConnection { Ok(()) } pub async fn connect(&self, port: u16, token: &str) -> Result<(), ConnectionError> { - Credential::new(port, token)?.validate()?; + let token = local_pairing_input(port, token)?; let access_token = timeout( Duration::from_secs(15), - self.transport.exchange_pairing(port, token), + self.transport.exchange_pairing(port, &token), ) .await .map_err(|_| ConnectionError::Transport)??; diff --git a/desktop/crates/bar-limits/src/live_tests.rs b/desktop/crates/bar-limits/src/live_tests.rs index 818f1e0..3de0f54 100644 --- a/desktop/crates/bar-limits/src/live_tests.rs +++ b/desktop/crates/bar-limits/src/live_tests.rs @@ -5,6 +5,60 @@ use std::{ sync::atomic::{AtomicUsize, Ordering}, }; +#[test] +fn local_pairing_links_accept_only_the_configured_loopback_destination() { + let port = 3773; + for address in ["127.0.0.1", "localhost", "[::1]"] { + let link = format!(" http://{address}:{port}/pair#token=abcd2345efgh "); + assert_eq!(local_pairing_input(port, &link).unwrap(), "ABCD2345EFGH"); + } + let direct = "http://127.0.0.1:3773/pair#token=ABCD2345EFGH"; + let desktop = format!( + "t3code://pair?pairingUrl={}", + url::form_urlencoded::byte_serialize(direct.as_bytes()).collect::() + ); + let hosted = "https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773#token=ABCD2345EFGH"; + for link in [&desktop, hosted] { + assert_eq!(local_pairing_input(port, link).unwrap(), "ABCD2345EFGH"); + } + for input in ["ABCD2345EFGH", "existing-access-token"] { + assert_eq!(local_pairing_input(port, input).unwrap(), input); + } + for link in [ + "http://127.0.0.1:3774/pair#token=ABCD2345EFGH", + "https://127.0.0.1:3773/pair#token=ABCD2345EFGH", + "https://remote.example/pair#token=ABCD2345EFGH", + "http://localhost.example:3773/pair#token=ABCD2345EFGH", + "https://app.t3.codes/pair?host=https%3A%2F%2Fremote.example#token=ABCD2345EFGH", + ] { + assert_eq!( + local_pairing_input(port, link), + Err(ConnectionError::PairingDestination) + ); + } +} + +#[test] +fn malformed_pairing_links_are_rejected_without_echoing_the_code() { + for link in [ + "http://127.0.0.1:3773/pair", + "http://127.0.0.1:3773/pair?token=ABCD2345EFGH", + "http://127.0.0.1:3773/pair#token=ABCD2345EFGH&token=ABCD2345EFGH", + "http://127.0.0.1:3773/pair#token=invalid", + "http://127.0.0.1:3773/oauth/token#token=ABCD2345EFGH", + "http://user:password@127.0.0.1:3773/pair#token=ABCD2345EFGH", + "t3code://pair?pairingUrl=invalid", + "t3code://pair?pairingUrl=one&pairingUrl=two", + "https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773&host=other#token=ABCD2345EFGH", + "https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773%2Fother#token=ABCD2345EFGH", + "http://", + ] { + let error = local_pairing_input(3773, link).unwrap_err(); + assert_eq!(error, ConnectionError::InvalidPairingLink); + assert!(!error.to_string().contains("ABCD2345EFGH")); + } +} + #[test] fn pairing_code_shape_matches_t3_code_and_bearer_tokens_pass_through() { assert!(is_pairing_code("ABCD2345EFGH")); @@ -200,15 +254,20 @@ fn write_frame(s: &mut std::net::TcpStream, value: &str) { } #[test] fn loopback_bootstrap_subscribe_ack_and_snapshot() { - loopback_connection(false); + loopback_connection(false, false); } #[test] fn loopback_pairing_saves_access_token_and_streams_limits() { - loopback_connection(true); + loopback_connection(true, false); +} + +#[test] +fn loopback_pairing_link_saves_only_the_exchanged_access_token() { + loopback_connection(true, true); } -fn loopback_connection(pairing: bool) { +fn loopback_connection(pairing: bool, link: bool) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let server = std::thread::spawn(move || { @@ -273,9 +332,12 @@ fn loopback_connection(pairing: bool) { runtime().block_on(async { let store = Arc::new(Memory::default()); let c = LimitsConnection::with_default_transport(store.clone()); + let pairing_link = format!("http://127.0.0.1:{port}/pair#token=ABCD2345EFGH"); c.connect( port, - if pairing { + if link { + &pairing_link + } else if pairing { "ABCD2345EFGH" } else { "test-token" @@ -348,10 +410,7 @@ fn saved_pairing_is_restored_offline_without_a_transport_request() { fn restore_storage_errors_are_explicit_and_do_not_fake_pairing() { let c = LimitsConnection::with_default_transport(Arc::new(BrokenStore)); assert_eq!(c.restore_saved(), Err(ConnectionError::Storage)); - assert_eq!( - c.snapshot().status, - LiveStatus::StorageUnavailable - ); + assert_eq!(c.snapshot().status, LiveStatus::StorageUnavailable); assert!(!c.snapshot().has_credential); } struct Mock { @@ -424,6 +483,16 @@ fn invalid_replacement_preserves_active_connection_and_saved_key() { }; assert_eq!(c.connect(43, "").await, Err(ConnectionError::InvalidToken)); + assert_eq!( + c.connect(43, "http://127.0.0.1:44/pair#token=ABCD2345EFGH") + .await, + Err(ConnectionError::PairingDestination) + ); + assert_eq!( + c.connect(43, "http://127.0.0.1:43/pair#token=invalid") + .await, + Err(ConnectionError::InvalidPairingLink) + ); assert_eq!( c.connect(43, "ABCD2345EFGH").await, Err(ConnectionError::PairingRejected) diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 448f86c..8dbf582 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -2591,6 +2591,21 @@ async fn connect( refresh_threads(&app, &state); result } +#[tauri::command] +async fn connect_from_clipboard( + state: State<'_, SharedState>, + app: tauri::AppHandle, +) -> Result<(), String> { + use tauri_plugin_clipboard_manager::ClipboardExt; + let token = app + .clipboard() + .read_text() + .map_err(|_| "Could not read the clipboard. Paste a pairing link or code into the field instead.")?; + if token.trim().is_empty() { + return Err("Copy a pairing link from T3 Code first.".into()); + } + connect(token, state, app).await +} #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ConnectionCandidate { @@ -3198,6 +3213,7 @@ fn main() { install_update, update_prompt_shown, connect, + connect_from_clipboard, reconnect, disconnect ]); diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 10f2d6e..9e26e1b 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -42,6 +42,7 @@ function Chevron({ right = false }: { right?: boolean }) { export function App() { const [snapshot, setSnapshot] = useState(null); const [screen, setScreen] = useState('threads'); + const [connectionSettings, setConnectionSettings] = useState(false); const [metric, setMetric] = useState('cost'); const [period, setPeriod] = useState('24h'); const [threadGeneration, setThreadGeneration] = useState(0); @@ -58,17 +59,18 @@ export function App() { const initial = invoke('get_snapshot').then(s => { if (!disposed) { setSnapshot(s); if (s.startupError) setError(s.startupError); } }).catch(e => { if (!disposed) setError(String(e)); }); const events = listen('bar-snapshot', e => { if (!disposed) setSnapshot(e.payload); }); const opened = listen('bar-opened', () => { setScreen(current => current === 'settings' ? current : 'threads'); setContext(null); setThreadGeneration(generation => generation + 1); }); - const settings = listen('bar-settings', () => setScreen('settings')); + const settings = listen('bar-settings', () => { setConnectionSettings(false); setScreen('settings'); }); void initial; return () => { disposed = true; void events.then(stop => stop()); void opened.then(stop => stop()); void settings.then(stop => stop()); }; }, []); useEffect(() => { void act('set_view', { screen, metric, period }); }, [screen, metric, period, act]); + useEffect(() => { if (screen !== 'settings') setConnectionSettings(false); }, [screen]); useEffect(() => { const update = snapshot?.update; - if (screen === 'settings' && update?.canInstall && update.offerId != null && update.version) { + if (screen === 'settings' && !connectionSettings && update?.canInstall && update.offerId != null && update.version) { void invoke('update_prompt_shown', { offerId: update.offerId, version: update.version }); } - }, [screen, snapshot?.update.offerId, snapshot?.update.version, snapshot?.update.canInstall]); + }, [screen, connectionSettings, snapshot?.update.offerId, snapshot?.update.version, snapshot?.update.canInstall]); useEffect(() => { if (!root.current) return; let timer: ReturnType; @@ -83,12 +85,13 @@ export function App() { const key = (event: KeyboardEvent) => { if (event.key !== 'Escape') return; if (context) setContext(null); + else if (screen === 'settings' && connectionSettings) setConnectionSettings(false); else if (screen !== 'threads') setScreen('threads'); else void act('hide_panel'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); - }, [screen, context, act]); + }, [screen, connectionSettings, context, act]); const hasThreadAccess = snapshot !== null && (snapshot.localConnection.paired || snapshot.connection.paired || snapshot.environments.some(environment => !environment.isLocal && (environment.status === 'online' || snapshot.threads.some(thread => thread.thread.environmentId === environment.id)))); @@ -96,7 +99,7 @@ export function App() { return
setContext(null)}> {error &&
{error}
} {!snapshot ? - : screen === 'settings' ? <>
Settings
+ : screen === 'settings' ? <>
{connectionSettings ? 'Local connection' : 'Settings'}
{connectionSettings ? : setConnectionSettings(true)} />} : !hasThreadAccess ?

Connect this computer

Pair with T3 Code on this computer to see your threads, replies and usage. Remote environments and T3 Connect sign-in are optional in Settings.
: screen === 'threads' ? <> @@ -133,8 +136,7 @@ function EnvironmentPicker({ snapshot, act }: { snapshot: AppSnapshot; act: Act } type Act = (name: string, args?: Record) => Promise; -function SettingsPage({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) { - const [confirmDisconnect, setConfirmDisconnect] = useState(false); +function SettingsPage({ snapshot, act, onManageConnection }: { snapshot: AppSnapshot; act: Act; onManageConnection: () => void }) { const [pending, setPending] = useState(false); const unavailable = snapshot.update.status === 'unavailable'; const updateBusy = snapshot.update.busy; @@ -144,14 +146,13 @@ function SettingsPage({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) { }; const toggle = (label: string, key: Exclude, checked: boolean, disabled = false, invert = false) => ; return
-

Local T3 Code connection

Pairing here connects Bar to this computer. Add other machines separately below. - {snapshot.localConnection.paired && (confirmDisconnect ?

Disconnect and remove the saved pairing key? You will need a new key to connect again.

: )} +

Local T3 Code connection

{snapshot.localConnection.connected ? 'Connected to T3 Code' : snapshot.localConnection.message}

Environment

Optional: import saved environments instead of adding their addresses manually. This may ask to read T3 Code’s encrypted connection list using its Keychain or Secret Service entry. Importing only discovers environments; each still needs its own Bar pairing. {toggle('Import environments from T3 Code', 'importsDesktopEnvironments', snapshot.settings.importsDesktopEnvironments)} Turning import off stops discovery from that list. Your saved Bar pairing credentials are not deleted. Local pairing, manually added environments and T3 Connect work without this import. - {snapshot.environments.map(environment => )} + {snapshot.environments.filter(environment => !environment.isLocal).map(environment => )}

T3 Connect

Sign in to find linked environments. Pair once with each environment to read through its public HTTPS tunnel. Tailscale is not required.{snapshot.cloudError && {snapshot.cloudError}}{snapshot.cloudStatus === 'signedOut' && }{snapshot.cloudStatus === 'signingIn' && }{snapshot.cloudStatus === 'signedIn' && }{snapshot.cloudStatus === 'recoveryRequired' && <>Saved T3 Connect credentials need recovery. Restore access to your system keyring, then retry sign out. Some saved credentials may remain until cleanup succeeds.}{snapshot.cloudStatus === 'unavailable' && T3 Connect unavailable}

Preferences

@@ -168,6 +169,14 @@ function SettingsPage({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) {
; } +function LocalConnectionSettings({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) { + const [confirmDisconnect, setConfirmDisconnect] = useState(false); + const [pending, setPending] = useState(false); + return
+ {snapshot.localConnection.paired && (confirmDisconnect ?

Disconnect and remove the saved pairing key? You will need a new key to connect again.

: )} +
; +} + function EnvironmentSelectionOptions({ snapshot, act }: { snapshot: AppSnapshot; act: Act }) { const [pending, setPending] = useState(false); const selectedId = snapshot.settings.environmentSelection === 'all' ? '' : snapshot.settings.environmentSelection.one; @@ -260,7 +269,7 @@ function Connection({ snapshot, act, compact: minimal = false, local = false }: const busy = pending || restoring || ['connecting', 'retrying'].includes(connection.status); useEffect(() => { if (connection.connected) { setToken(''); setExpanded(false); } }, [connection.connected]); useEffect(() => { if (!connection.paired && !minimal) setExpanded(true); }, [connection.paired, minimal]); - const connect = async (name: 'connect' | 'reconnect') => { + const connect = async (name: 'connect' | 'reconnect' | 'connect_from_clipboard') => { const input = token; setToken(''); setPending(true); @@ -273,10 +282,10 @@ function Connection({ snapshot, act, compact: minimal = false, local = false }: {storageUnavailable && } {!storageUnavailable && !restoring && connection.paired &&
} {!storageUnavailable && !restoring && !connection.paired && minimal && } - {!storageUnavailable && !restoring && expanded &&
{ e.preventDefault(); if (token.trim() && !busy) void connect('connect'); }}> - {local &&
  1. In T3 Code, open Settings → Sharing & access.
  2. Under Authorized clients, choose Create link with read-only permissions.
  3. Copy the one-time pairing code and paste it below.

Bar saves its own pairing credential in your OS credential store for reconnects. Local pairing does not need access to T3 Code’s saved environment key.

} - setToken(e.target.value)} /> -
+ {!storageUnavailable && !restoring && expanded && { e.preventDefault(); if (!busy && (local || token.trim())) void connect(token.trim() ? 'connect' : 'connect_from_clipboard'); }}> + {local &&
  1. In T3 Code, open Settings → Sharing & access.
  2. Under Authorized clients, choose Create link with read-only permissions.
  3. Choose Copy link, then Paste and connect here.

Or paste a link or use Copy code only below.

Clipboard access happens only on click. Bar saves its own access for reconnects.

} + setToken(e.target.value)} /> +
} }
; diff --git a/desktop/src/app-preview.test.tsx b/desktop/src/app-preview.test.tsx index 1f1857e..20ca83b 100644 --- a/desktop/src/app-preview.test.tsx +++ b/desktop/src/app-preview.test.tsx @@ -188,6 +188,49 @@ describe('thread preview lifecycle', () => { }); describe('new-install pairing', () => { + it('submits a complete pairing link without displaying or retaining it', async () => { + const value = snapshot(true); + value.localConnection = { ...value.localConnection, connected: false, paired: false }; + value.connection = { ...value.localConnection }; + await renderSnapshot(value); + const link = 'http://127.0.0.1:3773/pair#token=ABCD2345EFGH'; + const input = host.querySelector('input[type="password"]')!; + expect(host.querySelectorAll('form button')).toHaveLength(1); + expect(host.querySelector('form button')?.textContent).toBe('Paste and connect'); + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, link); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + expect(host.querySelectorAll('form button')).toHaveLength(1); + expect(host.querySelector('form button')?.textContent).toBe('Connect'); + await act(async () => { host.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); }); + expect(tauri.invoke).toHaveBeenCalledWith('connect', { token: link }); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'connect_from_clipboard')).toBe(false); + expect(input.value).toBe(''); + expect(host.textContent).not.toContain('ABCD2345EFGH'); + }); + + it('reads the clipboard only after an explicit click and keeps pairing failures visible', async () => { + const value = snapshot(true); + value.localConnection = { ...value.localConnection, connected: false, paired: false }; + value.connection = { ...value.localConnection }; + await renderSnapshot(value); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'connect_from_clipboard')).toBe(false); + expect(host.textContent).toContain('Copy link'); + expect(host.textContent).toContain('Copy code only'); + let rejectClipboard!: (error: string) => void; + tauri.invoke.mockImplementation((name: string) => name === 'connect_from_clipboard' + ? new Promise((_resolve, reject) => { rejectClipboard = reject; }) : Promise.resolve(null)); + const pasteButton = [...host.querySelectorAll('button')].find(button => button.textContent === 'Paste and connect')!; + await act(async () => pasteButton.click()); + expect(tauri.invoke).toHaveBeenCalledWith('connect_from_clipboard', undefined); + expect(pasteButton.disabled).toBe(true); + await act(async () => rejectClipboard('This link does not match the running local T3 Code server.')); + expect(host.querySelector('[role="alert"]')?.textContent).toContain('does not match'); + expect(pasteButton.disabled).toBe(false); + expect(host.querySelector('form')).not.toBeNull(); + }); + it('uses local pairing state even when discovery reports an aggregate connection', async () => { const value = snapshot(true); value.connection = { ...value.connection, connected: true, paired: false }; @@ -228,7 +271,7 @@ describe('new-install pairing', () => { await renderSnapshot(value); expect(host.querySelector('.onboarding')).not.toBeNull(); expect(host.querySelector('.thread-row')).toBeNull(); - expect(host.querySelector('input[type="password"]')?.getAttribute('placeholder')).toBe('Local pairing key'); + expect(host.querySelector('input[type="password"]')?.getAttribute('placeholder')).toBe('Paste pairing link or code'); expect(host.textContent).not.toContain('Auto-Generate'); const input = host.querySelector('input[type="password"]')!; @@ -263,6 +306,50 @@ describe('new-install pairing', () => { }); describe('settings state and actions', () => { + it('keeps onboarding out of Settings and pairs a needsAccess Local only through connect', async () => { + const value = snapshot(true); + value.localConnection = { ...value.localConnection, connected: false, paired: false, status: 'unpaired', message: 'Pair to give Bar read access.' }; + value.connection = { ...value.localConnection }; + value.environments = [{ id: 'local', label: 'Local', machine: 'laptop', status: 'needsAccess', access: 'direct', isLocal: true, canForgetAccess: false }]; + await renderSnapshot(value); + expect(host.querySelector('.onboarding')).not.toBeNull(); + act(() => button('Settings').click()); + expect(host.querySelector('.onboarding')).toBeNull(); + expect(host.querySelector('.pairing-help')).toBeNull(); + expect(host.querySelectorAll('form')).toHaveLength(0); + expect(host.textContent).toContain('Preferences'); + act(() => button('Manage connection').click()); + expect(host.querySelectorAll('form')).toHaveLength(1); + expect(host.querySelectorAll('input[type="password"]')).toHaveLength(1); + expect(host.textContent).not.toContain('Preferences'); + const input = host.querySelector('input[type="password"]')!; + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'ABCD2345EFGH'); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + await act(async () => button('Connect').click()); + expect(tauri.invoke).toHaveBeenCalledWith('connect', { token: 'ABCD2345EFGH' }); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'pair_environment')).toBe(false); + act(() => tauri.listeners.get('bar-opened')?.()); + expect(host.querySelectorAll('form')).toHaveLength(1); + act(() => host.querySelector('[aria-label="Back to settings"]')!.click()); + expect(host.querySelectorAll('form')).toHaveLength(0); + act(() => button('Manage connection').click()); + act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))); + expect(host.querySelectorAll('form')).toHaveLength(0); + expect(host.textContent).toContain('Preferences'); + }); + + it.each(['permissionDenied', 'restoring', 'credentialUnavailable'] as const)('keeps Local %s recovery out of remote controls', async status => { + const value = snapshot(true); + value.localConnection = { ...value.localConnection, connected: false, status, message: 'Local recovery is needed.' }; + value.environments = [{ id: 'local', label: 'Local', machine: 'laptop', status, access: 'direct', isLocal: true, canForgetAccess: false }]; + await openSettings(value); + expect(host.querySelector('.environment-access')).toBeNull(); + expect(host.querySelectorAll('form')).toHaveLength(0); + expect(host.textContent).toContain('Local recovery is needed.'); + }); + it('puts local pairing before remote settings and enables desktop imports only on request', async () => { await openSettings(); expect(host.querySelector('.settings section h2')?.textContent).toBe('Local T3 Code connection'); @@ -325,6 +412,7 @@ describe('settings state and actions', () => { }); it('hides pairing while connected and requires confirmation before removing the key', async () => { await openSettings(); + act(() => button('Manage connection').click()); expect(host.querySelector('input[type="password"]')).toBeNull(); expect(host.textContent).toContain('Connected to T3 Code'); act(() => button('Disconnect…').click()); @@ -348,6 +436,7 @@ describe('settings state and actions', () => { value.localConnection = { ...value.connection }; await openSettings(value); expect(host.querySelector('input[type="password"]')).toBeNull(); + act(() => button('Manage connection').click()); await act(async () => button('Reconnect').click()); expect(tauri.invoke).toHaveBeenCalledWith('reconnect', undefined); act(() => button('Pair again…').click()); @@ -425,8 +514,11 @@ describe('environment sources', () => { await renderSnapshot(value); act(() => [...host.querySelectorAll('button')].find(button => button.textContent === 'Settings')!.click()); expect(host.textContent).toContain('Local T3 Code connection'); - expect(host.querySelector('label[for="access-token"]')?.textContent).toBe('Local pairing key'); expect(host.textContent).toContain('Remote Mac pairing key'); + expect(host.querySelector('label[for="access-token"]')).toBeNull(); + act(() => [...host.querySelectorAll('button')].find(button => button.textContent === 'Manage connection')!.click()); + expect(host.querySelector('label[for="access-token"]')?.textContent).toBe('Local pairing link or code'); + expect(host.textContent).not.toContain('Remote Mac pairing key'); }); it('routes needsAccess by route capability without leaking pairing forms', async () => { diff --git a/docs/USAGE.md b/docs/USAGE.md index 7fefa6f..21313fe 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1,8 +1,12 @@ # Usage -Start T3 Code, then launch the Bar. In T3 Code, open **Settings → Sharing & access → Authorized clients → Create link** and choose read-only permissions. Copy its one-time pairing code into **Local pairing key** in the Bar, then click **Connect**. The Bar saves its own pairing credential in its OS credential namespace for later reconnects. OS permission approval and discovering a running T3 Code server do not complete pairing. +Start T3 Code, then launch the Bar. In T3 Code, open **Settings → Sharing & access → Authorized clients → Create link** and choose read-only permissions. Choose **Copy link**, then **Paste and connect** in the Bar. Alternatively, paste the full link or use **Copy code only** in the **Local pairing link or code** field and click **Connect**. The clipboard is read only when you click **Paste and connect**, never in the background. The Bar saves its own pairing credential in its OS credential namespace for later reconnects. OS permission approval and discovering a running T3 Code server do not complete pairing. -Local setup does not require T3 Connect sign-in or access to T3 Code's saved environment key. Settings puts **Local T3 Code connection** first. Add a remote environment manually by address or SSH host, or sign in to T3 Connect to find linked environments. +Local pairing links must target the running local T3 Code server's loopback address and port. Links for other machines or stale ports are rejected before sending the code; use **Add environment** for remote connections. The local parser accepts direct HTTP loopback `/pair#token=…` links and their `t3code://pair?pairingUrl=…` or hosted `https://app.t3.codes/pair?host=…#token=…` wrappers without opening them or following redirects. Link format evidence: T3 Code v0.1.9, `apps/web/src/components/settings/pairingUrls.ts`. + +The pairing form has one action: **Paste and connect** when the field is empty, or **Connect** after entering a link or code. + +Local setup does not require T3 Connect sign-in or access to T3 Code's saved environment key. Settings shows a compact **Local T3 Code connection** status. Choose **Manage connection** to open its dedicated pairing, reconnect and disconnect page; the back button returns to Settings. Local never appears in the remote pairing controls. Add a remote environment manually by address or SSH host, or sign in to T3 Connect to find linked environments. **Import environments from T3 Code** in Settings is optional and off by default, including after upgrading from a version without this preference. Turn it on only if you want the Bar to discover T3 Code's saved connections. Reading that encrypted list may require approval for T3 Code's Keychain or Secret Service entry; it discovers metadata and routes, not read authorization. Pair separately with each environment. Turning import off stops catalog discovery without deleting Bar's saved credentials. Imported-only environments may become unavailable until you turn import back on or add their route manually. Manual connections and T3 Connect discovery are independent of this preference. From 6687c627cb0a62f3e97484eecf6139860caddec1 Mon Sep 17 00:00:00 2001 From: wang2 <134143178+fatwang2@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:53:26 +0800 Subject: [PATCH 3/3] feat: unify local and remote pairing-link onboarding --- CHANGELOG.md | 4 +- desktop/crates/bar-connection/src/manual.rs | 33 +++ desktop/src-tauri/src/main.rs | 233 ++++++++++++++++---- desktop/src/App.tsx | 30 ++- desktop/src/app-preview.test.tsx | 61 +++-- docs/COMPATIBILITY.md | 8 + docs/USAGE.md | 6 +- 7 files changed, 302 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47f535b..fd90605 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This log records user-visible changes. GitHub releases contain package downloads ### Changed -- Start onboarding with local pairing instructions and a single connection action. Settings shows a compact local status with a separate Manage connection page. +- Start onboarding with one pairing-link entry for local or remote environments and show Settings after pairing. Settings shows a compact local status with a separate Manage connection page. - Exclude Local from remote pairing controls so an unpaired local server cannot submit through the remote-only pairing command. -- Accept complete local pairing links and add an explicit Paste and connect action; reject links for other destinations before exchanging the code. +- Identify the link's environment before pairing, select it after connecting, and support remote-only installations without local T3 Code state. - Make importing T3 Code's encrypted environment catalog opt-in; preserve Bar's own pairing credentials and independent manual and T3 Connect connections. - Distinguish a running local server from an authorized Bar connection instead of showing unpaired installations as connected. diff --git a/desktop/crates/bar-connection/src/manual.rs b/desktop/crates/bar-connection/src/manual.rs index 112490d..80073a2 100644 --- a/desktop/crates/bar-connection/src/manual.rs +++ b/desktop/crates/bar-connection/src/manual.rs @@ -48,6 +48,15 @@ pub fn input_has_pairing_key(input: &ConnectionInput) -> Result { Ok(parse_input(input)?.code.is_some()) } +pub fn pairing_key_from_link(input: &ConnectionInput) -> Result { + let parsed = parse_input(input)?; + let code = parsed.code.ok_or("Copy a complete pairing link from T3 Code, including its one-time code.")?; + if code.len() != 12 || !code.chars().all(|character| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(character.to_ascii_uppercase())) { + return Err("This pairing link has an invalid code. Create and copy a fresh link in T3 Code.".into()); + } + Ok(PairingKey::new(code.to_ascii_uppercase())) +} + struct ParsedInput { route: Route, code: Option>, @@ -130,6 +139,9 @@ fn parse_input(input: &ConnectionInput) -> Result { url.set_path("/"); } url.set_fragment(None); + if url.scheme() == "http" && url.host_str() == Some("localhost") { + url.set_host(Some("127.0.0.1")).map_err(|_| invalid_input())?; + } let base = crate::normalized_origin(url.as_str()).map_err(|_| invalid_input())?; Ok(ParsedInput { route: Route::Bearer { @@ -737,6 +749,27 @@ mod tests { .is_err()); } + #[test] + fn unified_pairing_requires_a_complete_link_and_normalizes_localhost() { + for address in [ + "https://remote.example/", + "https://remote.example/pair#token=invalid", + "https://remote.example/pair#token=ABCD2345EFGH&token=ABCD2345EFGH", + "ABCD2345EFGH", + ] { + let input = ConnectionInput::Direct { address: address.into() }; + assert!(pairing_key_from_link(&input).is_err()); + } + for address in [ + "http://localhost:3773/pair#token=abcd2345efgh", + "t3code://pair?pairingUrl=http%3A%2F%2Flocalhost%3A3773%2Fpair%23token%3DABCD2345EFGH", + ] { + let input = ConnectionInput::Direct { address: address.into() }; + assert_eq!(pairing_key_from_link(&input).unwrap().as_str(), "ABCD2345EFGH"); + assert_eq!(destination_label(&input_route(&input).unwrap()), "http://127.0.0.1:3773/"); + } + } + #[test] fn manual_and_desktop_routes_deduplicate_and_removal_leaves_desktop_untouched() { let dir = FixtureDir::new(); diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 8dbf582..d1c18bc 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -893,10 +893,10 @@ fn refresh_cloud_directory(state: &RuntimeState) { fn merge_cloud_directory( entries: &mut Vec, directory: Vec, - local: &EnvironmentId, + local: Option<&EnvironmentId>, ) { for discovered in directory { - if &discovered.id == local { + if Some(&discovered.id) == local { continue; } if let Some(entry) = entries.iter_mut().find(|entry| entry.id == discovered.id) { @@ -931,20 +931,19 @@ fn discover_sources(state: &RuntimeState) -> Result<(), String> { // The caller holds manual_connection_gate across metadata projection and publication. fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { use bar_core::environments::DiscoveryState; - let local = local_environment(&state.config)?; - let mut primary = EnvironmentMetadata { - id: local.clone(), + let local = local_environment(&state.config).ok(); + let primary: Vec<_> = local.iter().map(|id| EnvironmentMetadata { + id: id.clone(), label: "Local".into(), enabled: true, - routes: Vec::new(), - }; - if let Ok(port) = state.config.server_port() { - primary.routes.push(Route::Primary { + routes: state.config.server_port().ok().map(|port| Route::Primary { http_base_url: format!("http://127.0.0.1:{port}"), - }); - } + }).into_iter().collect(), + }).collect(); let mut paths = HashMap::new(); - paths.insert(local.clone(), state.config.clone()); + if let Some(local) = &local { + paths.insert(local.clone(), state.config.clone()); + } let imports_desktop_environments = state .hub .lock() @@ -958,7 +957,7 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { ) .map_err(|e| e.to_string())? .into_entries(); - let mut metadata = vec![primary.clone()]; + let mut metadata = primary.clone(); let seed_codes = !state .fixture_pairing_seeded .swap(true, std::sync::atomic::Ordering::AcqRel); @@ -991,16 +990,16 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { } Ok(metadata) } else { - Ok(vec![primary.clone()]) + Ok(primary.clone()) } - } else if imports_desktop_environments { + } else if imports_desktop_environments && !primary.is_empty() { bar_core::connection::catalog::discover( &state.config.base_dir.join("connection-catalog.json"), - primary.clone(), + primary[0].clone(), ) .map_err(|_| ()) } else { - Ok(vec![primary.clone()]) + Ok(primary.clone()) }; let directory = state.cloud_directory.lock().ok() .filter(|cache| cache.generation == state.cloud_generation.load(std::sync::atomic::Ordering::Acquire)) @@ -1017,19 +1016,19 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { match entries { Ok(mut entries) => { *catalog = entries.clone(); - merge_cloud_directory(&mut entries, directory, &local); + merge_cloud_directory(&mut entries, directory, local.as_ref()); Ok(registry.merge(entries)) } Err(_) if !registry.entries().is_empty() || !catalog.is_empty() => { let mut known = catalog.clone(); - known.retain(|entry| entry.id != local); - known.push(primary.clone()); - merge_cloud_directory(&mut known, directory, &local); + known.retain(|entry| Some(&entry.id) != local.as_ref()); + known.extend(primary.clone()); + merge_cloud_directory(&mut known, directory, local.as_ref()); Ok(registry.merge(known)) } Err(_) if !directory.is_empty() => { - let mut known = vec![primary.clone()]; - merge_cloud_directory(&mut known, directory, &local); + let mut known = primary.clone(); + merge_cloud_directory(&mut known, directory, local.as_ref()); Ok(registry.merge(known)) } Err(error) => Err(error), @@ -1037,7 +1036,7 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { }; let mut hub = state.hub.lock().map_err(|_| "environments unavailable")?; if matches!(hub.discovery_state(), DiscoveryState::Pending) - || (entries.is_err() && !hub.sources().contains_key(&local)) + || (entries.is_err() && local.as_ref().is_some_and(|local| !hub.sources().contains_key(local))) { let mut known: Vec<_> = hub .sources() @@ -1045,18 +1044,20 @@ fn discover_sources_locked(state: &RuntimeState) -> Result<(), String> { .filter(|source| source.present) .map(|source| source.metadata.clone()) .collect(); - known.push(primary); + known.extend(primary); hub.apply_discovery(Ok(known)); } hub.apply_discovery(entries); - hub.set_machine( - &local, - Some(environment_metadata::local_machine( - &state.config.base_dir, - state.descriptor_machine.lock().ok().and_then(|m| *m), - )), - None, - ); + if let Some(local) = &local { + hub.set_machine( + local, + Some(environment_metadata::local_machine( + &state.config.base_dir, + state.descriptor_machine.lock().ok().and_then(|m| *m), + )), + None, + ); + } for id in paths.keys() { if hub .sources() @@ -2283,13 +2284,18 @@ fn set_environment_selection( state: State<'_, SharedState>, app: tauri::AppHandle, ) -> Result<(), String> { + select_environment(&state, selection)?; + emit_snapshot(&app, &state); + Ok(()) +} + +fn select_environment(state: &RuntimeState, selection: EnvironmentSelection) -> Result<(), String> { let mut hub = state.hub.lock().map_err(|_| "settings unavailable")?; let mut snapshot = state.snapshot.lock().map_err(|_| "snapshot unavailable")?; snapshot.revision = hub.set_selection(selection).map_err(|e| e.to_string())?; snapshot.settings = hub.settings().clone(); drop(snapshot); drop(hub); - emit_snapshot(&app, &state); Ok(()) } #[tauri::command] @@ -2577,19 +2583,76 @@ async fn connect( state: State<'_, SharedState>, app: tauri::AppHandle, ) -> Result<(), String> { - let generation = begin_connection_operation(&state); + let result = connect_local(&state, &token).await; + refresh_threads(&app, &state); + result +} + +async fn connect_local(state: &SharedState, token: &str) -> Result<(), String> { + let generation = begin_connection_operation(state); let port = state.config.server_port().map_err(|e| e.to_string())?; let _gate = state.connection_gate.lock().await; - if !connection_operation_current(&state, generation) { + if !connection_operation_current(state, generation) { return Ok(()); } - let result = state + state .connection - .connect(port, &token) + .connect(port, token) .await - .map_err(|e| e.to_string()); + .map_err(|e| e.to_string()) +} + +enum PairingLinkConnection { + Local(EnvironmentId, bar_core::connection::manual::PairingKey), + Remote(EnvironmentId), +} + +fn pair_link_environment( + state: &RuntimeState, + input: &bar_core::connection::manual::ConnectionInput, +) -> Result { + let code = bar_core::connection::manual::pairing_key_from_link(input)?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| "Connection runtime unavailable")?; + let metadata = runtime.block_on(bar_core::connection::manual::probe(input, &state.ssh_options))?; + if local_environment(&state.config).ok().as_ref() == Some(&metadata.id) { + return Ok(PairingLinkConnection::Local(metadata.id, code)); + } + save_manual_connection(state, input, &metadata.id, String::new())?; + Ok(PairingLinkConnection::Remote(metadata.id)) +} + +#[tauri::command] +async fn connect_pairing_link( + link: Option, + state: State<'_, SharedState>, + app: tauri::AppHandle, +) -> Result<(), String> { + use tauri_plugin_clipboard_manager::ClipboardExt; + let address = match link { + Some(link) => link, + None => app.clipboard().read_text().map_err(|_| "Could not read the clipboard. Paste the pairing link into the field instead.")?, + }; + if address.trim().is_empty() { + return Err("Copy a pairing link from T3 Code first.".into()); + } + let input = bar_core::connection::manual::ConnectionInput::Direct { address }; + let worker_state = Arc::clone(&state); + let connection = tauri::async_runtime::spawn_blocking(move || pair_link_environment(&worker_state, &input)) + .await.map_err(|_| "Could not connect to this environment")??; + let environment = match connection { + PairingLinkConnection::Local(environment, code) => { + connect_local(&state, code.as_str()).await?; + environment + } + PairingLinkConnection::Remote(environment) => environment, + }; + select_environment(&state, EnvironmentSelection::One(environment))?; + emit_snapshot(&app, &state); refresh_threads(&app, &state); - result + Ok(()) } #[tauri::command] async fn connect_from_clipboard( @@ -2620,7 +2683,7 @@ fn validate_connection_identity( environment: &EnvironmentId, route: &Route, ) -> Result<(), String> { - if local_environment(&state.config)? == *environment { + if local_environment(&state.config).ok().as_ref() == Some(environment) { return Err( "This is the Local environment. Use the Local T3 Code connection below.".into(), ); @@ -3213,6 +3276,7 @@ fn main() { install_update, update_prompt_shown, connect, + connect_pairing_link, connect_from_clipboard, reconnect, disconnect @@ -3454,7 +3518,7 @@ mod tests { enabled: true, routes: vec![], }]; - merge_cloud_directory(&mut entries, directory.clone(), &local); + merge_cloud_directory(&mut entries, directory.clone(), Some(&local)); assert_eq!(entries.len(), 2); assert!(entries[0].routes.is_empty()); assert_eq!( @@ -3464,7 +3528,7 @@ mod tests { entries[1].label = "Desktop label".into(); entries[1].enabled = false; entries[1].routes.push(Route::Relay); - merge_cloud_directory(&mut entries, directory, &local); + merge_cloud_directory(&mut entries, directory, Some(&local)); assert!(!entries[1].enabled); assert_eq!(entries[1].label, "Desktop label"); assert_eq!(entries[1].routes, vec![public]); @@ -4603,6 +4667,89 @@ while True: .any(|environment| environment.id == id)); assert!(!root.path().join("connection-catalog.json").exists()); } + + #[test] + fn unified_link_pairs_remote_without_any_local_t3_installation() { + let root = tempfile::tempdir().unwrap(); + let state = ssh_state(root.path(), SshConnectOptions::default()); + let server = token_server("remote-only"); + let input = bar_core::connection::manual::ConnectionInput::Direct { + address: format!("http://127.0.0.1:{}/pair#token=ABCD2345EFGH", server.port), + }; + let result = pair_link_environment(&state, &input).unwrap(); + let PairingLinkConnection::Remote(environment) = result else { panic!("Expected remote pairing") }; + assert_eq!(environment.as_str(), "remote-only"); + assert_eq!(server.exchanges.load(Ordering::SeqCst), 1); + assert!(!state.connection.snapshot().has_credential); + select_environment(&state, EnvironmentSelection::One(environment.clone())).unwrap(); + assert_eq!(state.hub.lock().unwrap().settings().environment_selection, EnvironmentSelection::One(environment.clone())); + let route = state.remote_routes.lock().unwrap()[&environment][0].clone(); + assert!(grant_with(&state, &runtime(), &environment, &route, None).is_ok()); + let registry = std::fs::read_to_string(root.path().join("connections.json")).unwrap(); + assert!(!registry.contains("ABCD2345EFGH")); + assert!(!registry.contains("#token")); + assert!(!root.path().join("environment-id").exists()); + } + + #[test] + fn unified_link_uses_verified_identity_for_local_pairing() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("environment-id"), "local-link").unwrap(); + let state = ssh_state(root.path(), SshConnectOptions::default()); + let server = token_server("local-link"); + std::fs::write(root.path().join("server-runtime.json"), format!(r#"{{"port":{}}}"#, server.port)).unwrap(); + let input = bar_core::connection::manual::ConnectionInput::Direct { + address: format!("http://localhost:{}/pair#token=ABCD2345EFGH", server.port), + }; + let result = pair_link_environment(&state, &input).unwrap(); + let PairingLinkConnection::Local(environment, code) = result else { panic!("Expected local pairing") }; + assert_eq!(environment.as_str(), "local-link"); + assert_eq!(server.exchanges.load(Ordering::SeqCst), 0); + runtime().block_on(connect_local(&state, code.as_str())).unwrap(); + assert!(state.connection.snapshot().has_credential); + assert_eq!(server.exchanges.load(Ordering::SeqCst), 1); + assert!(state.manual_connections.lock().unwrap().entries().is_empty()); + } + + #[test] + fn unified_link_never_falls_back_to_local_for_a_remote_environment() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("environment-id"), "local-present").unwrap(); + let local = token_server("local-present"); + let remote = token_server("remote-target"); + std::fs::write(root.path().join("server-runtime.json"), format!(r#"{{"port":{}}}"#, local.port)).unwrap(); + let state = ssh_state(root.path(), SshConnectOptions::default()); + let input = bar_core::connection::manual::ConnectionInput::Direct { + address: format!("http://127.0.0.1:{}/pair#token=ABCD2345EFGH", remote.port), + }; + assert!(matches!(pair_link_environment(&state, &input).unwrap(), PairingLinkConnection::Remote(environment) if environment.as_str() == "remote-target")); + assert_eq!(local.exchanges.load(Ordering::SeqCst), 0); + assert_eq!(remote.exchanges.load(Ordering::SeqCst), 1); + assert!(!state.connection.snapshot().has_credential); + } + + #[test] + fn unified_link_never_sends_invalid_codes_or_reassigns_an_existing_route() { + let root = tempfile::tempdir().unwrap(); + let state = ssh_state(root.path(), SshConnectOptions::default()); + let server = token_server("changed-identity"); + for suffix in ["/", "/pair#token=invalid"] { + let input = bar_core::connection::manual::ConnectionInput::Direct { + address: format!("http://127.0.0.1:{}{suffix}", server.port), + }; + assert!(pair_link_environment(&state, &input).is_err()); + } + let input = bar_core::connection::manual::ConnectionInput::Direct { + address: format!("http://127.0.0.1:{}/pair#token=ABCD2345EFGH", server.port), + }; + state.remote_routes.lock().unwrap().insert( + EnvironmentId::new("previous-identity").unwrap(), + vec![bar_core::connection::manual::input_route(&input).unwrap()], + ); + assert!(pair_link_environment(&state, &input).is_err()); + assert_eq!(server.exchanges.load(Ordering::SeqCst), 0); + assert!(state.manual_connections.lock().unwrap().entries().is_empty()); + } #[test] fn forgetting_removes_only_that_environments_access_and_drops_its_session() { let dir = tempfile::tempdir().unwrap(); diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 9e26e1b..9291004 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -48,6 +48,8 @@ export function App() { const [threadGeneration, setThreadGeneration] = useState(0); const [error, setError] = useState(null); const [context, setContext] = useState<{ thread: ThreadItem } | null>(null); + const hasThreadAccess = snapshot !== null && (snapshot.localConnection.paired || snapshot.connection.paired || snapshot.environments.some(environment => + !environment.isLocal && (environment.status === 'online' || snapshot.threads.some(thread => thread.thread.environmentId === environment.id)))); const root = useRef(null); const act = useCallback(async (name: string, args?: Record) => { try { setError(null); await invoke(name, args); } @@ -65,12 +67,13 @@ export function App() { }, []); useEffect(() => { void act('set_view', { screen, metric, period }); }, [screen, metric, period, act]); useEffect(() => { if (screen !== 'settings') setConnectionSettings(false); }, [screen]); + useEffect(() => { if (snapshot && !hasThreadAccess) { setScreen('threads'); setConnectionSettings(false); } }, [snapshot, hasThreadAccess, screen]); useEffect(() => { const update = snapshot?.update; - if (screen === 'settings' && !connectionSettings && update?.canInstall && update.offerId != null && update.version) { + if (hasThreadAccess && screen === 'settings' && !connectionSettings && update?.canInstall && update.offerId != null && update.version) { void invoke('update_prompt_shown', { offerId: update.offerId, version: update.version }); } - }, [screen, connectionSettings, snapshot?.update.offerId, snapshot?.update.version, snapshot?.update.canInstall]); + }, [hasThreadAccess, screen, connectionSettings, snapshot?.update.offerId, snapshot?.update.version, snapshot?.update.canInstall]); useEffect(() => { if (!root.current) return; let timer: ReturnType; @@ -93,14 +96,11 @@ export function App() { return () => window.removeEventListener('keydown', key); }, [screen, connectionSettings, context, act]); - const hasThreadAccess = snapshot !== null && (snapshot.localConnection.paired || snapshot.connection.paired || snapshot.environments.some(environment => - !environment.isLocal && (environment.status === 'online' || snapshot.threads.some(thread => thread.thread.environmentId === environment.id)))); - return
setContext(null)}> {error &&
{error}
} {!snapshot ? + : !hasThreadAccess ?

Connect to T3 Code

Paste a pairing link from the environment you want to connect. It can be on this computer or another machine.
: screen === 'settings' ? <>
{connectionSettings ? 'Local connection' : 'Settings'}
{connectionSettings ? : setConnectionSettings(true)} />} - : !hasThreadAccess ?

Connect this computer

Pair with T3 Code on this computer to see your threads, replies and usage. Remote environments and T3 Connect sign-in are optional in Settings.
: screen === 'threads' ? <>
@@ -136,6 +136,24 @@ function EnvironmentPicker({ snapshot, act }: { snapshot: AppSnapshot; act: Act } type Act = (name: string, args?: Record) => Promise; +function PairingLinkConnection({ act }: { act: Act }) { + const [link, setLink] = useState(''); + const [pending, setPending] = useState(false); + return
{ + event.preventDefault(); + if (pending) return; + const input = link.trim() || null; + setLink(''); + setPending(true); + void act('connect_pairing_link', { link: input }).finally(() => setPending(false)); + }}> + + setLink(event.target.value)} /> +
+

Clipboard access happens only when you choose Paste and connect.

+
; +} + function SettingsPage({ snapshot, act, onManageConnection }: { snapshot: AppSnapshot; act: Act; onManageConnection: () => void }) { const [pending, setPending] = useState(false); const unavailable = snapshot.update.status === 'unavailable'; diff --git a/desktop/src/app-preview.test.tsx b/desktop/src/app-preview.test.tsx index 20ca83b..ce2f3be 100644 --- a/desktop/src/app-preview.test.tsx +++ b/desktop/src/app-preview.test.tsx @@ -188,12 +188,11 @@ describe('thread preview lifecycle', () => { }); describe('new-install pairing', () => { - it('submits a complete pairing link without displaying or retaining it', async () => { + it.each(['http://127.0.0.1:3773/pair#token=ABCD2345EFGH', 'https://remote.example/pair#token=ABCD2345EFGH'])('submits %s through the unified link command without retaining it', async link => { const value = snapshot(true); value.localConnection = { ...value.localConnection, connected: false, paired: false }; value.connection = { ...value.localConnection }; await renderSnapshot(value); - const link = 'http://127.0.0.1:3773/pair#token=ABCD2345EFGH'; const input = host.querySelector('input[type="password"]')!; expect(host.querySelectorAll('form button')).toHaveLength(1); expect(host.querySelector('form button')?.textContent).toBe('Paste and connect'); @@ -204,8 +203,8 @@ describe('new-install pairing', () => { expect(host.querySelectorAll('form button')).toHaveLength(1); expect(host.querySelector('form button')?.textContent).toBe('Connect'); await act(async () => { host.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); }); - expect(tauri.invoke).toHaveBeenCalledWith('connect', { token: link }); - expect(tauri.invoke.mock.calls.some(([name]) => name === 'connect_from_clipboard')).toBe(false); + expect(tauri.invoke).toHaveBeenCalledWith('connect_pairing_link', { link }); + expect(tauri.invoke.mock.calls.some(([name, args]) => name === 'connect_pairing_link' && args?.link === null)).toBe(false); expect(input.value).toBe(''); expect(host.textContent).not.toContain('ABCD2345EFGH'); }); @@ -215,15 +214,15 @@ describe('new-install pairing', () => { value.localConnection = { ...value.localConnection, connected: false, paired: false }; value.connection = { ...value.localConnection }; await renderSnapshot(value); - expect(tauri.invoke.mock.calls.some(([name]) => name === 'connect_from_clipboard')).toBe(false); + expect(tauri.invoke.mock.calls.some(([name]) => name === 'connect_pairing_link')).toBe(false); expect(host.textContent).toContain('Copy link'); - expect(host.textContent).toContain('Copy code only'); + expect(host.textContent).not.toContain('Copy code only'); let rejectClipboard!: (error: string) => void; - tauri.invoke.mockImplementation((name: string) => name === 'connect_from_clipboard' + tauri.invoke.mockImplementation((name: string) => name === 'connect_pairing_link' ? new Promise((_resolve, reject) => { rejectClipboard = reject; }) : Promise.resolve(null)); const pasteButton = [...host.querySelectorAll('button')].find(button => button.textContent === 'Paste and connect')!; await act(async () => pasteButton.click()); - expect(tauri.invoke).toHaveBeenCalledWith('connect_from_clipboard', undefined); + expect(tauri.invoke).toHaveBeenCalledWith('connect_pairing_link', { link: null }); expect(pasteButton.disabled).toBe(true); await act(async () => rejectClipboard('This link does not match the running local T3 Code server.')); expect(host.querySelector('[role="alert"]')?.textContent).toContain('does not match'); @@ -238,13 +237,13 @@ describe('new-install pairing', () => { value.environments = [{ id: 'local', label: 'Local', machine: 'laptop', status: 'online', access: 'direct', isLocal: true, canForgetAccess: false }]; await renderSnapshot(value); expect(host.querySelector('.onboarding')).not.toBeNull(); - expect(host.textContent).toContain('Connect this computer'); + expect(host.textContent).toContain('Connect to T3 Code'); expect(host.textContent).toContain('Settings → Sharing & access'); expect(host.textContent).toContain('Authorized clients'); expect(host.textContent).toContain('Create link'); expect(host.textContent).not.toContain('Connected to T3 Code'); const input = host.querySelector('input[type="password"]'); - expect(input?.getAttribute('aria-describedby')).toBe('local-pairing-help'); + expect(input?.getAttribute('aria-describedby')).toBe('pairing-link-help'); expect(host.querySelectorAll('form')).toHaveLength(1); expect(tauri.invoke.mock.calls.some(([name]) => name === 'begin_cloud_login')).toBe(false); expect(tauri.invoke).not.toHaveBeenCalledWith('set_setting', expect.anything()); @@ -264,23 +263,23 @@ describe('new-install pairing', () => { expect(host.querySelector('[aria-label="Environment selector"]')).not.toBeNull(); }); - it('requires a pairing key even when T3 Code already has cached data', async () => { + it('requires a pairing link even when T3 Code already has cached data', async () => { const value = snapshot(true); value.connection = { ...value.connection, connected: false, paired: false, status: 'cacheOnly' }; value.localConnection = { ...value.connection }; await renderSnapshot(value); expect(host.querySelector('.onboarding')).not.toBeNull(); expect(host.querySelector('.thread-row')).toBeNull(); - expect(host.querySelector('input[type="password"]')?.getAttribute('placeholder')).toBe('Paste pairing link or code'); + expect(host.querySelector('input[type="password"]')?.getAttribute('placeholder')).toBe('Paste pairing link'); expect(host.textContent).not.toContain('Auto-Generate'); const input = host.querySelector('input[type="password"]')!; act(() => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'synthetic-pairing-key'); + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'https://remote.example/pair#token=ABCD2345EFGH'); input.dispatchEvent(new Event('input', { bubbles: true })); }); await act(async () => { host.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); }); - expect(tauri.invoke).toHaveBeenCalledWith('connect', { token: 'synthetic-pairing-key' }); + expect(tauri.invoke).toHaveBeenCalledWith('connect_pairing_link', { link: 'https://remote.example/pair#token=ABCD2345EFGH' }); expect(input.value).toBe(''); act(() => tauri.listeners.get('bar-snapshot')?.({ payload: snapshot(true) })); @@ -306,14 +305,35 @@ describe('new-install pairing', () => { }); describe('settings state and actions', () => { + it('removes Settings before pairing, including native menu requests', async () => { + const value = snapshot(true); + value.localConnection = { ...value.localConnection, connected: false, paired: false }; + value.connection = { ...value.localConnection }; + value.environments = []; + await renderSnapshot(value); + expect(host.querySelectorAll('button')).toHaveLength(1); + expect(host.querySelector('.settings')).toBeNull(); + act(() => tauri.listeners.get('bar-settings')?.()); + expect(host.querySelector('.settings')).toBeNull(); + expect(host.querySelectorAll('form')).toHaveLength(1); + const paired = { ...value, environments: [{ id: 'remote', label: 'Remote', machine: 'server', status: 'online', access: 'direct' as const, isLocal: false, canForgetAccess: true }] }; + act(() => tauri.listeners.get('bar-snapshot')?.({ payload: paired })); + expect(host.querySelector('.onboarding')).toBeNull(); + act(() => tauri.listeners.get('bar-settings')?.()); + expect(host.querySelector('.settings')).not.toBeNull(); + }); + it('keeps onboarding out of Settings and pairs a needsAccess Local only through connect', async () => { const value = snapshot(true); value.localConnection = { ...value.localConnection, connected: false, paired: false, status: 'unpaired', message: 'Pair to give Bar read access.' }; value.connection = { ...value.localConnection }; - value.environments = [{ id: 'local', label: 'Local', machine: 'laptop', status: 'needsAccess', access: 'direct', isLocal: true, canForgetAccess: false }]; + value.environments = [ + { id: 'local', label: 'Local', machine: 'laptop', status: 'needsAccess', access: 'direct', isLocal: true, canForgetAccess: false }, + { id: 'remote-ready', label: 'Remote', machine: 'server', status: 'online', access: 'direct', isLocal: false, canForgetAccess: true }, + ]; await renderSnapshot(value); - expect(host.querySelector('.onboarding')).not.toBeNull(); - act(() => button('Settings').click()); + expect(host.querySelector('.onboarding')).toBeNull(); + act(() => host.querySelector('[aria-label="Settings"]')!.click()); expect(host.querySelector('.onboarding')).toBeNull(); expect(host.querySelector('.pairing-help')).toBeNull(); expect(host.querySelectorAll('form')).toHaveLength(0); @@ -510,9 +530,12 @@ describe('environment sources', () => { value.connection = { ...value.connection, connected: false, paired: false, status: 'disconnected' }; value.localConnection = { ...value.connection }; value.settings.environmentSelection = { one: 'remote' }; - value.environments = [{ id: 'remote', label: 'Remote Mac', machine: 'laptop', status: 'needsAccess', access: 'direct', isLocal: false, canForgetAccess: false }]; + value.environments = [ + { id: 'remote', label: 'Remote Mac', machine: 'laptop', status: 'needsAccess', access: 'direct', isLocal: false, canForgetAccess: false }, + { id: 'other', label: 'Other', machine: 'server', status: 'online', access: 'direct', isLocal: false, canForgetAccess: true }, + ]; await renderSnapshot(value); - act(() => [...host.querySelectorAll('button')].find(button => button.textContent === 'Settings')!.click()); + act(() => host.querySelector('[aria-label="Settings"]')!.click()); expect(host.textContent).toContain('Local T3 Code connection'); expect(host.textContent).toContain('Remote Mac pairing key'); expect(host.querySelector('label[for="access-token"]')).toBeNull(); diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index b9769eb..de623a9 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -15,6 +15,14 @@ The Tauri bundle identity and credential namespace differ from Swift v1. Existin ## Multiple environments on Linux and macOS +First setup accepts a complete pairing link for either a local or a remote +environment. Bar identifies the destination before exchanging its code, routes a +matching local identity to the local credential store, and saves other identities +as manual remote connections. Remote-only installations do not need a local +environment ID, database or running T3 Code process. Bare codes and server origins +are insufficient for this first-run flow. Settings becomes available after pairing; +its existing manual address, SSH and T3 Connect controls remain available there. + Settings selects All environments or one environment. The selection applies to threads, Usage, Limits and notifications, and survives restart. A missing selected environment stays selected. Thread actions use both environment and diff --git a/docs/USAGE.md b/docs/USAGE.md index 21313fe..6b6e234 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1,10 +1,10 @@ # Usage -Start T3 Code, then launch the Bar. In T3 Code, open **Settings → Sharing & access → Authorized clients → Create link** and choose read-only permissions. Choose **Copy link**, then **Paste and connect** in the Bar. Alternatively, paste the full link or use **Copy code only** in the **Local pairing link or code** field and click **Connect**. The clipboard is read only when you click **Paste and connect**, never in the background. The Bar saves its own pairing credential in its OS credential namespace for later reconnects. OS permission approval and discovering a running T3 Code server do not complete pairing. +Launch the Bar. In the T3 Code environment you want to connect, open **Settings → Sharing & access → Authorized clients → Create link** and choose read-only permissions. Choose **Copy link**, then **Paste and connect** in the Bar. Alternatively, paste the complete link into **Pairing link** and click **Connect**. The same entry connects this computer or a remote machine; a remote connection does not require a local T3 Code installation. The clipboard is read only after an explicit action, never in the background. Bar saves its own grant for later reconnects. -Local pairing links must target the running local T3 Code server's loopback address and port. Links for other machines or stale ports are rejected before sending the code; use **Add environment** for remote connections. The local parser accepts direct HTTP loopback `/pair#token=…` links and their `t3code://pair?pairingUrl=…` or hosted `https://app.t3.codes/pair?host=…#token=…` wrappers without opening them or following redirects. Link format evidence: T3 Code v0.1.9, `apps/web/src/components/settings/pairingUrls.ts`. +Bar validates the destination and identifies the environment before exchanging the code. A verified local identity uses the local connection; other identities are paired and saved as remote environments. Bar selects the connected environment automatically. Remote addresses must be reachable and follow the existing HTTPS, loopback or verified Tailscale transport policy. A localhost link copied from another computer still points to this computer: create a link with that server's reachable address. Supported formats include direct `/pair#token=…` links, `t3code://pair?pairingUrl=…` wrappers, and hosted `https://app.t3.codes/pair?host=…#token=…` links. Link format evidence: T3 Code v0.1.9, `apps/web/src/components/settings/pairingUrls.ts`. -The pairing form has one action: **Paste and connect** when the field is empty, or **Connect** after entering a link or code. +First setup has one action: **Paste and connect** when the field is empty, or **Connect** after entering a link. A bare pairing code is insufficient here because it does not identify the target. Settings is available after pairing, not during first setup. Previously paired installations keep recovery and Settings available while offline. Local setup does not require T3 Connect sign-in or access to T3 Code's saved environment key. Settings shows a compact **Local T3 Code connection** status. Choose **Manage connection** to open its dedicated pairing, reconnect and disconnect page; the back button returns to Settings. Local never appears in the remote pairing controls. Add a remote environment manually by address or SSH host, or sign in to T3 Connect to find linked environments.