Skip to content

Commit 4a916ba

Browse files
authored
Show ChatGPT login URL during onboarding (openai#2028)
## Summary - display authentication URL in the ChatGPT sign-in screen while onboarding <img width="684" height="151" alt="image" src="https://github.com/user-attachments/assets/a8c32cb0-77f6-4a3f-ae3b-6695247c994d" />
1 parent 0091930 commit 4a916ba

File tree

3 files changed

+89
-26
lines changed

3 files changed

+89
-26
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
- [Quickstart](#quickstart)
1919
- [Installing and running Codex CLI](#installing-and-running-codex-cli)
2020
- [Using Codex with your ChatGPT plan](#using-codex-with-your-chatgpt-plan)
21+
- [Connecting through VPS or remote](#connecting-through-vps-or-remote)
2122
- [Usage-based billing alternative: Use an OpenAI API key](#usage-based-billing-alternative-use-an-openai-api-key)
2223
- [Choosing Codex's level of autonomy](#choosing-codexs-level-of-autonomy)
2324
- [**1. Read/write**](#1-readwrite)
@@ -108,6 +109,17 @@ After you run `codex` select Sign in with ChatGPT. You'll need a Plus, Pro, or T
108109
109110
If you encounter problems with the login flow, please comment on [this issue](https://github.com/openai/codex/issues/1243).
110111

112+
### Connecting through VPS or remote
113+
114+
If you run Codex on a remote machine (VPS/server) without a local browser, the login helper starts a server on `localhost:1455` on the remote host. To complete login in your local browser, forward that port to your machine before starting the login flow:
115+
116+
```bash
117+
# From your local machine
118+
ssh -L 1455:localhost:1455 <user>@<remote-host>
119+
```
120+
121+
Then, in that SSH session, run `codex` and select "Sign in with ChatGPT". When prompted, open the printed URL (it will be `http://localhost:1455/...`) in your local browser. The traffic will be tunneled to the remote server.
122+
111123
### Usage-based billing alternative: Use an OpenAI API key
112124

113125
If you prefer to pay-as-you-go, you can still authenticate with your OpenAI API key by setting it as an environment variable:

codex-rs/login/src/lib.rs

Lines changed: 49 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::fs::OpenOptions;
99
use std::fs::remove_file;
1010
use std::io::Read;
1111
use std::io::Write;
12+
use std::io::{self};
1213
#[cfg(unix)]
1314
use std::os::unix::fs::OpenOptionsExt;
1415
use std::path::Path;
@@ -262,6 +263,50 @@ pub struct SpawnedLogin {
262263
pub stderr: Arc<Mutex<Vec<u8>>>,
263264
}
264265

266+
impl SpawnedLogin {
267+
/// Returns the login URL, if one has been emitted by the login subprocess.
268+
///
269+
/// The Python helper prints the URL to stderr; we capture it and extract
270+
/// the last whitespace-separated token that starts with "http".
271+
pub fn get_login_url(&self) -> Option<String> {
272+
self.stderr
273+
.lock()
274+
.ok()
275+
.and_then(|buffer| String::from_utf8(buffer.clone()).ok())
276+
.and_then(|output| {
277+
output
278+
.split_whitespace()
279+
.filter(|part| part.starts_with("http"))
280+
.next_back()
281+
.map(|s| s.to_string())
282+
})
283+
}
284+
}
285+
286+
// Helpers for streaming child output into shared buffers
287+
struct AppendWriter {
288+
buf: Arc<Mutex<Vec<u8>>>,
289+
}
290+
291+
impl Write for AppendWriter {
292+
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
293+
if let Ok(mut b) = self.buf.lock() {
294+
b.extend_from_slice(data);
295+
}
296+
Ok(data.len())
297+
}
298+
299+
fn flush(&mut self) -> io::Result<()> {
300+
Ok(())
301+
}
302+
}
303+
304+
fn spawn_pipe_reader<R: Read + Send + 'static>(mut reader: R, buf: Arc<Mutex<Vec<u8>>>) {
305+
std::thread::spawn(move || {
306+
let _ = io::copy(&mut reader, &mut AppendWriter { buf });
307+
});
308+
}
309+
265310
/// Spawn the ChatGPT login Python server as a child process and return a handle to its process.
266311
pub fn spawn_login_with_chatgpt(codex_home: &Path) -> std::io::Result<SpawnedLogin> {
267312
let script_path = write_login_script_to_disk()?;
@@ -278,25 +323,11 @@ pub fn spawn_login_with_chatgpt(codex_home: &Path) -> std::io::Result<SpawnedLog
278323
let stdout_buf = Arc::new(Mutex::new(Vec::new()));
279324
let stderr_buf = Arc::new(Mutex::new(Vec::new()));
280325

281-
if let Some(mut out) = child.stdout.take() {
282-
let buf = stdout_buf.clone();
283-
std::thread::spawn(move || {
284-
let mut tmp = Vec::new();
285-
let _ = std::io::copy(&mut out, &mut tmp);
286-
if let Ok(mut b) = buf.lock() {
287-
b.extend_from_slice(&tmp);
288-
}
289-
});
326+
if let Some(out) = child.stdout.take() {
327+
spawn_pipe_reader(out, stdout_buf.clone());
290328
}
291-
if let Some(mut err) = child.stderr.take() {
292-
let buf = stderr_buf.clone();
293-
std::thread::spawn(move || {
294-
let mut tmp = Vec::new();
295-
let _ = std::io::copy(&mut err, &mut tmp);
296-
if let Ok(mut b) = buf.lock() {
297-
b.extend_from_slice(&tmp);
298-
}
299-
});
329+
if let Some(err) = child.stderr.take() {
330+
spawn_pipe_reader(err, stderr_buf.clone());
300331
}
301332

302333
Ok(SpawnedLogin {

codex-rs/tui/src/onboarding/auth.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use super::onboarding_screen::StepState;
3030
#[derive(Debug)]
3131
pub(crate) enum SignInState {
3232
PickMode,
33-
ChatGptContinueInBrowser(#[allow(dead_code)] ContinueInBrowserState),
33+
ChatGptContinueInBrowser(ContinueInBrowserState),
3434
ChatGptSuccessMessage,
3535
ChatGptSuccess,
3636
EnvVarMissing,
@@ -40,12 +40,12 @@ pub(crate) enum SignInState {
4040
#[derive(Debug)]
4141
/// Used to manage the lifecycle of SpawnedLogin and FrameTicker and ensure they get cleaned up.
4242
pub(crate) struct ContinueInBrowserState {
43-
_login_child: Option<codex_login::SpawnedLogin>,
43+
login_child: Option<codex_login::SpawnedLogin>,
4444
_frame_ticker: Option<FrameTicker>,
4545
}
4646
impl Drop for ContinueInBrowserState {
4747
fn drop(&mut self) {
48-
if let Some(child) = &self._login_child {
48+
if let Some(child) = &self.login_child {
4949
if let Ok(mut locked) = child.child.lock() {
5050
// Best-effort terminate and reap the child to avoid zombies.
5151
let _ = locked.kill();
@@ -183,11 +183,31 @@ impl AuthModeWidget {
183183
let idx = self.current_frame();
184184
let mut spans = vec![Span::from("> ")];
185185
spans.extend(shimmer_spans("Finish signing in via your browser", idx));
186-
let lines = vec![
187-
Line::from(spans),
188-
Line::from(""),
186+
let mut lines = vec![Line::from(spans), Line::from("")];
187+
188+
if let SignInState::ChatGptContinueInBrowser(state) = &self.sign_in_state {
189+
if let Some(url) = state
190+
.login_child
191+
.as_ref()
192+
.and_then(|child| child.get_login_url())
193+
{
194+
lines.push(Line::from(" If the link doesn't open automatically, open the following link to authenticate:"));
195+
lines.push(Line::from(vec![
196+
Span::raw(" "),
197+
Span::styled(
198+
url,
199+
Style::default()
200+
.fg(LIGHT_BLUE)
201+
.add_modifier(Modifier::UNDERLINED),
202+
),
203+
]));
204+
lines.push(Line::from(""));
205+
}
206+
}
207+
208+
lines.push(
189209
Line::from(" Press Esc to cancel").style(Style::default().add_modifier(Modifier::DIM)),
190-
];
210+
);
191211
Paragraph::new(lines)
192212
.wrap(Wrap { trim: false })
193213
.render(area, buf);
@@ -276,7 +296,7 @@ impl AuthModeWidget {
276296
self.spawn_completion_poller(child.clone());
277297
self.sign_in_state =
278298
SignInState::ChatGptContinueInBrowser(ContinueInBrowserState {
279-
_login_child: Some(child),
299+
login_child: Some(child),
280300
_frame_ticker: Some(FrameTicker::new(self.event_tx.clone())),
281301
});
282302
self.event_tx.send(AppEvent::RequestRedraw);

0 commit comments

Comments
 (0)