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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ The common ones:
| `CODETRIAL_MAX_CONCURRENT_INTERVIEWS` | `16` | Interviews one `web` process hosts agents for |
| `CODETRIAL_ALLOWED_HOSTS` | empty | Comma-separated `Host` values the server answers; any other is refused with 421. Empty answers every name, but a value that names no host is refused at startup. `--allowed-hosts` sets it from the command line |
| `CODETRIAL_EXIT_WITH_STDIN` | unset | For a program that starts the server as its child: exit when standard input reaches end of file, so the server does not outlive a launcher that crashed. Read from the process environment even under `--data-dir` |
| `CODETRIAL_CHANGE_KEYS_CODE` | unset | For a program that starts the server as its child: the Change keys code, at least 24 letters and digits, which the server then never prints. Read from the process environment even under `--data-dir`; ignored by a launch from a terminal, which makes and prints its own |

Two more matter in production. `SESSION_SECRET` signs the session cookie, and
its built-in default is a string published in this repository, so the server
Expand Down
1 change: 1 addition & 0 deletions desktop/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions desktop/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ all = "deny"
tauri-build = { version = "=2.7.4", features = [] }

[dependencies]
# Already in the tree through tauri; the Change keys code is read from it.
getrandom = "=0.3.4"
open = { version = "=5.4.4", features = ["shellexecute-on-windows"] }
tauri = { version = "=2.12.5", features = [] }
tauri-plugin-dialog = "=2.8.4"
Expand Down
54 changes: 52 additions & 2 deletions desktop/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ use std::path::Path;
use std::sync::{LazyLock, Mutex, mpsc};
use std::time::Duration;

use tauri::webview::{DownloadEvent, NewWindowResponse, PermissionKind, PermissionResponse};
use tauri::webview::{
DownloadEvent, NewWindowResponse, PageLoadEvent, PermissionKind, PermissionResponse,
};
use tauri::{AppHandle, Manager, RunEvent, Url, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};

use navigation::{Ask, Verdict};
use navigation::{Ask, ChangeKeysCode, Verdict};

const WINDOW: &str = "main";

Expand Down Expand Up @@ -89,6 +91,8 @@ enum Close {

struct Shell {
server: Mutex<Option<server::Server>>,
/// The running server's Change keys code, shown or filled in this window.
change_keys_code: Mutex<Option<String>>,
phase: Mutex<Phase>,
close: Mutex<Close>,
}
Expand All @@ -113,6 +117,7 @@ fn main() {
.plugin(tauri_plugin_dialog::init())
.manage(Shell {
server: Mutex::new(None),
change_keys_code: Mutex::new(None),
phase: Mutex::new(Phase::Starting {
server_ready: false,
webrtc: None,
Expand Down Expand Up @@ -208,6 +213,27 @@ fn open_window(app: &AppHandle) -> tauri::Result<()> {
Verdict::Refuse => false,
}
})
// Change keys asks for the code the server would print to a terminal,
// and this server has none. With the interview in this window the code
// is filled into the server's own Setup page and no other; with it in
// the browser, the start page left here shows it, as a terminal would.
// Never in a URL, where history would keep it.
.on_page_load(|webview, payload| {
if payload.event() != PageLoadEvent::Finished {
return;
}
let script =
match navigation::change_keys_code_for(payload.url(), &SERVER_URL, &START_PAGE) {
Some(ChangeKeysCode::Fill) => fill_change_keys_code,
Some(ChangeKeysCode::Show) => show_change_keys_code,
None => return,
};
let shell = webview.app_handle().state::<Shell>();
let code = shell.change_keys_code.lock().expect("code lock").clone();
if let Some(code) = code {
let _ = webview.eval(script(&code));
Comment thread
Patriciaath999 marked this conversation as resolved.
Resolved
}
})
// `target="_blank"` and `window.open`. A second webview would be a
// second window into the same origin with none of the rules above, so a
// web page goes to the browser and nothing opens here.
Expand Down Expand Up @@ -300,6 +326,7 @@ fn launch(app: &AppHandle) {
std::fs::create_dir_all(&data_dir)
.map_err(|error| format!("cannot create {}: {error}", data_dir.display()))?;
Ok(server::Launch {
change_keys_code: server::change_keys_code()?,
program: server::program_path()?,
data_dir,
addr: SERVER_ADDR.to_string(),
Expand All @@ -313,6 +340,10 @@ fn launch(app: &AppHandle) {
Err(message) => return show_failure(app, &message, None),
};

*app.state::<Shell>()
.change_keys_code
.lock()
.expect("code lock") = Some(launch.change_keys_code.clone());
let data_dir = launch.data_dir.clone();
let reporter = app.clone();
let started = server::start(&launch, move |status| {
Expand Down Expand Up @@ -342,6 +373,25 @@ fn launch(app: &AppHandle) {
}
}

/// The script that puts `code`, hex digits only, into the Setup page's code
/// field. The page shows and enables that field itself once `/api/setup`
/// answers, which keeps the value, so the field appears already filled.
fn fill_change_keys_code(code: &str) -> String {
format!(
"(() => {{ const field = document.getElementById('code'); \
if (field) field.value = '{code}'; }})()"
)
}

/// The script that shows `code`, hex digits only, on the start page when the
/// interview runs in the browser, where nothing here can fill it in.
fn show_change_keys_code(code: &str) -> String {
format!(
"(() => {{ document.getElementById('change-keys-code').textContent = '{code}'; \
document.getElementById('change-keys').hidden = false; }})()"
)
}

/// Shows the server in this window, or in the default browser when this
/// window has no WebRTC, once both halves are known: the server is ready and
/// the starting page has said what it has. Called as each arrives, in either
Expand Down
23 changes: 23 additions & 0 deletions desktop/src/navigation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,29 @@ pub fn judge(url: &Url, server: &Url, start_page: &Url) -> Verdict {
}
}

/// What a page the window finished loading is handed of the Change keys code.
#[derive(Debug, PartialEq, Eq)]
pub enum ChangeKeysCode {
/// Filled into the code field of the server's own Setup page.
Fill,
/// Shown on the start page left in the window while the interview runs in
/// the browser, where nothing here can fill a field.
Show,
}

/// Which pages get the code, and no other: a mistake here either hides Change
/// keys or hands the code to a page that is not the server's Setup page. Built
/// on `judge`, so a page the window may not show never gets it.
pub fn change_keys_code_for(url: &Url, server: &Url, start_page: &Url) -> Option<ChangeKeysCode> {
match judge(url, server, start_page) {
Verdict::Server if url.path() == "/setup" => Some(ChangeKeysCode::Fill),
Verdict::StartPage(Ask::Nothing) if url.query_pairs().any(|(key, _)| key == "browser") => {
Some(ChangeKeysCode::Show)
}
_ => None,
}
}

/// Where the window's start page loads, `http_scheme` being true on Windows
/// and Android. Tauri serves `WebviewUrl::App("index.html")` at the root of
/// its own origin, `http://tauri.localhost/` there and `tauri://localhost/`
Expand Down
14 changes: 14 additions & 0 deletions desktop/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ pub struct Launch {
/// A CLI config whose keys Setup offers to use on a first launch. The
/// server decides what is offered and what using it writes.
pub import_config: Option<PathBuf>,
/// What Change keys asks for, new on every launch. The server has no
/// terminal to print one to, so the app makes it, hands it over in the
/// environment, and shows or fills it in its own window.
pub change_keys_code: String,
}

/// A code for `Launch::change_keys_code`: 32 hex digits from the operating
/// system's generator.
pub fn change_keys_code() -> Result<String, String> {
let mut bytes = [0u8; 16];
getrandom::fill(&mut bytes)
.map_err(|error| format!("cannot make a Change keys code: {error}"))?;
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}

/// The CLI config in `start`: the CLI's own two places there and nowhere else.
Expand Down Expand Up @@ -116,6 +129,7 @@ fn command(launch: &Launch) -> Command {
// data folder is the one place it can sensibly mean.
.current_dir(&launch.data_dir)
.env("CODETRIAL_EXIT_WITH_STDIN", "1")
.env("CODETRIAL_CHANGE_KEYS_CODE", &launch.change_keys_code)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
Expand Down
44 changes: 44 additions & 0 deletions desktop/tests/unit/navigation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,47 @@ fn a_download_keeps_its_name_and_never_overwrites() {

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn only_the_servers_setup_page_and_the_browser_start_page_get_the_code() {
let server = url("http://127.0.0.1:3101/");
for start in [
"tauri://localhost/index.html",
"http://tauri.localhost/index.html",
] {
let start = url(start);
let code_for = |page: &str| change_keys_code_for(&url(page), &server, &start);
assert_eq!(
code_for("http://127.0.0.1:3101/setup"),
Some(ChangeKeysCode::Fill)
);

// `show_start_page` loads the root with the query, which serves
// `index.html`; the named file is the same page.
for shown in ["/?browser=", "index.html?browser="] {
assert_eq!(
code_for(start.join(shown).unwrap().as_str()),
Some(ChangeKeysCode::Show),
"{shown}"
);
}

// The server's own `?browser` is just a server page, and only its Setup
// page has the field: not another path, not another port, not the start
// page while it is starting, failing or asking.
for nothing in [
"http://127.0.0.1:3101/?browser=",
"http://127.0.0.1:3101/",
"http://127.0.0.1:3101/setup/x",
"http://127.0.0.1:3102/setup",
"http://localhost:3101/setup",
] {
assert_eq!(code_for(nothing), None, "{nothing}");
}
for query in ["", "?error=x", "?webrtc=no", "?reopen", "?browser=&reopen"] {
let page = start.join(&format!("index.html{query}")).unwrap();
assert_eq!(code_for(page.as_str()), None, "{page}");
}
assert_eq!(code_for(start.join("setup").unwrap().as_str()), None);
}
}
22 changes: 19 additions & 3 deletions desktop/tests/unit/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::sync::mpsc;

use super::*;

const CODE: &str = "0123456789abcdef0123456789abcdef";

fn temp_dir(label: &str) -> PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
Expand All @@ -22,6 +24,7 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() {
data_dir: PathBuf::from("/data"),
addr: "127.0.0.1:3101".to_string(),
import_config: None,
change_keys_code: CODE.to_string(),
};
let command = command(&launch);
let args = command
Expand All @@ -43,17 +46,18 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() {
);
assert_eq!(command.get_current_dir(), Some(Path::new("/data")));

// The pipe is the one thing it is told through the environment, which a
// `--data-dir` launch reads no configuration from.
// The pipe and the Change keys code are the two things it is told through
// the environment, which a `--data-dir` launch reads no configuration from.
let env = |key: &str| {
command
.get_envs()
.find(|(name, _)| *name == key)
.and_then(|(_, value)| value)
.map(|value| value.to_string_lossy().into_owned())
};
assert_eq!(command.get_envs().count(), 1);
assert_eq!(command.get_envs().count(), 2);
assert_eq!(env("CODETRIAL_EXIT_WITH_STDIN").as_deref(), Some("1"));
assert_eq!(env("CODETRIAL_CHANGE_KEYS_CODE").as_deref(), Some(CODE));
}

#[test]
Expand All @@ -63,6 +67,7 @@ fn a_cli_config_found_is_offered_to_the_server_to_import() {
data_dir: PathBuf::from("/data"),
addr: "127.0.0.1:3101".to_string(),
import_config: Some(PathBuf::from("/checkout/config/codetrial.env.local")),
change_keys_code: CODE.to_string(),
};
let args = command(&launch)
.get_args()
Expand Down Expand Up @@ -144,6 +149,7 @@ fn launch_of(dir: &Path, program: PathBuf, addr: String) -> Launch {
data_dir: dir.to_path_buf(),
addr,
import_config: None,
change_keys_code: CODE.to_string(),
}
}

Expand Down Expand Up @@ -218,3 +224,13 @@ fn a_server_is_ready_once_bound_and_stops_when_its_stdin_closes() {
assert!(received.recv_timeout(Duration::from_millis(500)).is_err());
let _ = std::fs::remove_dir_all(&dir);
}

/// Strong enough for the server to take: it ignores a code shorter than 24
/// letters and digits.
#[test]
fn a_change_keys_code_is_new_hex_on_every_launch() {
let first = change_keys_code().unwrap();
assert_eq!(first.len(), 32);
assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit()));
assert_ne!(first, change_keys_code().unwrap());
}
5 changes: 5 additions & 0 deletions desktop/ui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ <h1>CodeTrial</h1>
<p>
Keep this window open while you practise. Closing it stops CodeTrial.
</p>
<p id="change-keys" hidden>
When the lobby there offers Change keys, enter
<code id="change-keys-code"></code> as its code. It is new every time
CodeTrial starts.
</p>
</section>
<section id="failure" hidden>
<p>CodeTrial could not start.</p>
Expand Down
20 changes: 15 additions & 5 deletions docs/desktop.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ the binary's: `src/main.rs` runs the Setup handover and binds the socket, and
builds the server from `src/launch.rs` (config search, every refusal it makes
before serving). Calling that from the app would have meant a second launcher
beside the one the CLI's behavior is pinned to. As a child it is the binary the CLI
tests already cover, started with five things a launcher needs that the CLI
tests already cover, started with six things a launcher needs that the CLI
did not have. Each is decided in the server, so the app keeps no copy of the
server's rules:

Expand Down Expand Up @@ -69,15 +69,24 @@ server's rules:
quitting or by crashing, the server goes too and does not keep the port.
This one stays in the environment even for `--data-dir`, because it is not
configuration but a description of the pipe the launcher handed over.
- `CODETRIAL_CHANGE_KEYS_CODE`: the code Change keys asks for, which a
terminal launch prints and a child has no terminal to print to. The app
makes a new one on every launch, the server takes it only when it is at
least 24 letters and digits, and never prints it. The app fills it into the
Setup page in its own window, or, with the interview in the browser, shows
it on the page it leaves in its window. Read from the environment for the
same reason as the pipe above.
- `--no-update-check`: the lobby never offers a newer release, whatever the
config file says about `CODETRIAL_UPDATE_CHECK`. That check compares the
server with the `latest` release, and the app is published as
`desktop-latest`, so it would offer every desktop install an update to the
CLI binary.

All five are ordinary server options, and a CLI install can use them the same
way. `codetrial --help` lists the four flags, and the README's configuration
table lists `CODETRIAL_ALLOWED_HOSTS`.
All six are ordinary server options, and a CLI install can use them the same
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
way, except that the server takes `CODETRIAL_CHANGE_KEYS_CODE` only when
`CODETRIAL_EXIT_WITH_STDIN` says it was started as a child: a launch from a
terminal makes and prints its own code. `codetrial --help` lists the four
flags, and the README's configuration table lists `CODETRIAL_ALLOWED_HOSTS`.

## Where it keeps things

Expand All @@ -94,7 +103,8 @@ session signing key and a roaming profile is copied to a server:
In it:

- `codetrial.env.local`: the keys the Setup page takes, in plain text, the
same file the CLI writes. Edit it to change a key or add an option. The first
same file the CLI writes. Change keys in the lobby rewrites its keys, which
take effect when the app next starts; edit it to add an option. The first
launch writes it from exported LiveKit keys without asking (see `--data-dir`
above); otherwise Setup asks, and offers to use a CLI config found in the
folder the app was started in (see `--import-config`). An app opened from the Dock,
Expand Down
10 changes: 10 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,16 @@ pub fn exit_with_stdin(value: Option<&str>) -> bool {
parse_bool(value, false)
}

/// `CODETRIAL_CHANGE_KEYS_CODE`: the code the desktop app hands its child.
/// One too short to stand in for the code `run_web` makes is no code, so a
/// launcher that set it carelessly gets no Change keys rather than a weak one.
pub fn change_keys_code(value: Option<&str>) -> Option<String> {
value
.map(str::trim)
.filter(|code| code.len() >= 24 && code.bytes().all(|byte| byte.is_ascii_alphanumeric()))
.map(str::to_string)
}

pub fn gemini_candidate_video_enabled(value: Option<&str>) -> bool {
parse_bool(value, DEFAULT_GEMINI_CANDIDATE_VIDEO_ENABLED)
}
Expand Down
Loading
Loading