Skip to content
Closed
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
10 changes: 10 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Normalise text files in the repository and convert on checkout.
#
# Without this, line-ending behaviour depends on each contributor's global
# core.autocrlf, so the same file is CRLF for one person and LF for the next.
# Edits made by tooling that writes LF then land inside a CRLF working tree,
# and every subsequent commit warns "LF will be replaced by CRLF".
#
# `text=auto` keeps binary files untouched and lets git detect them, so this is
# safe to apply repository-wide.
* text=auto
43 changes: 43 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,49 @@

Thanks for contributing.

## Optional Nix development shell

If you already use Nix, run `nix develop` from the repository root. The
`flake.nix` provides Rust, Cargo, rustfmt, Clippy, rust-analyzer, the platform
C/C++ compiler, CMake, Make, Perl, pkg-config, OpenSSL, Git, and ripgrep.
On macOS it also supplies libclang through the bindgen hook for CoreAudio.
It declares shells for x86_64 and aarch64 Linux and macOS. This is a development
environment for the CLI repository, not Jcode Desktop or a Nix release package.
The existing non-Nix setup remains supported.

Enable `nix-command` and `flakes` in your Nix configuration, or use:

```sh
nix --extra-experimental-features 'nix-command flakes' develop
```

Inside the shell, use the normal development workflow. If you have `justrust`
installed, use `justrust check` and `justrust test`. The shell does not install
justrust or configure its hosted service. The Nix-provided Cargo also works for
contributors without justrust. Leave the shell with `exit`.

`flake.lock` pins nixpkgs, including the Rust toolchain and native libraries.
`Cargo.lock` still pins Rust crates. The shell does not replace your rustup
installation or make builds hermetic: it retains your environment and may use
externally installed tools. Optional integrations and runtime tools are not
all bundled.

To update the pinned environment deliberately:

```sh
nix flake update
nix flake check --all-systems
nix develop --command rustc --version
nix develop --command pkg-config --modversion openssl
nix develop --command justrust check
# Without justrust: nix develop --command cargo check
```

Review and commit the resulting `flake.lock` change. Add new native build
requirements to `flake.nix` when the project needs them. `flake check` evaluates
the shells but does not compile Jcode or prove that every declared platform
works, so test on the platforms you are changing as well.

## Issues vs pull requests

Both issues and pull requests are welcome. Open an issue to report a bug or discuss an idea, or send a focused PR if you have a fix or improvement ready. For large changes, discuss the approach in an issue first to avoid spending time on work that may not fit the project.
Expand Down
2 changes: 1 addition & 1 deletion crates/jcode-fuzzy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl PositionTracker for Vec<usize> {
self.len()
}
fn first_pos(&self) -> Option<usize> {
self.as_slice().first().copied()
self.first().copied()
}
}

Expand Down
109 changes: 109 additions & 0 deletions docs/GOOGLE_GUIDED_SETUP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Guided Google Setup (Bring-Your-Own OAuth App)

Status: plan. Depends on the generalized Google login (`--google-services`)
and a reliable browser tool.

## Decision

Every user authorizes jcode's Google integrations (Gmail, Calendar, later
Drive/Docs) through **their own Google Cloud OAuth app** in the `direct`
backend. jcode does not ship a shared Google OAuth client and does not route
Google data through a third party by default.

jcode removes the setup pain by **driving the Google Cloud Console setup with
the browser tool**, so the user only signs in and approves screens.

### Why not the alternatives

| Option | Problem |
|---|---|
| Shared jcode-owned verified app | Gmail scopes (`gmail.readonly`, `gmail.modify`, `gmail.compose`) are *restricted*: Google verification plus a yearly CASA assessment (roughly $540+/yr, weeks of review). Calendar alone is only *sensitive* (free review), so this stays an option for Calendar later. |
| Composio (`JCODE_GMAIL_BACKEND=composio`) | Every request and its payload goes through Composio's proxy, and Composio holds every user's Google refresh token. Consent screen shows "Composio". Shared quota, external dependency. Kept as opt-in only. See `GMAIL_COMPOSIO_BACKEND.md`. |
| `gog` CLI | Extra install, still bring-your-own app, and its file keyring needs `GOG_KEYRING_PASSWORD` in non-interactive agent shells. |

### Why bring-your-own works

- One user per app, so the 100-test-user cap never applies.
- No verification or CASA: the user is authorizing their own app.
- Traffic is machine to Google only. Tokens live in `~/.jcode/google_oauth.json` (0600).
- Adding services (Calendar, Drive, ...) needs no review, just enabling the API and re-consenting.

## Flow

Triggered when a Google tool (`gmail`, `calendar`) is called with no
credentials, or when the user asks to set up Google. The agent runs it with
the browser tool, in the user's normal browser profile where they are already
signed in to Google.

1. **Pick the account and services.** Confirm which Google account and which
services (`gmail`, `calendar`). Default to both so the user only goes
through the console once.
2. **Create a project.** `https://console.cloud.google.com/projectcreate`,
name `jcode`. Wait for creation and select the project.
3. **Enable APIs** for every selected service, up front:
- Gmail: `https://console.cloud.google.com/apis/library/gmail.googleapis.com`
- Calendar: `https://console.cloud.google.com/apis/library/calendar-json.googleapis.com`
4. **Configure the consent screen** (Google Auth Platform / OAuth consent screen):
- User type: External (Internal is fine for Workspace accounts that allow it).
- App name `jcode`, support and developer email = the user's email.
- Do not add scopes here. jcode requests them at login.
5. **Publish the app** (Audience page, "Publish app" / "In production").
This is required. In "Testing" mode Google expires refresh tokens after
**7 days**, which forces a weekly re-login. Personal-use published apps do
not need verification.
6. **Create the OAuth client.** Credentials, Create credentials, OAuth client
ID, application type **Desktop app**, name `jcode`. jcode's loopback
redirect (`http://127.0.0.1:<port>`) works with Desktop clients without
registering redirect URIs.
7. **Save credentials.** Read the client ID and secret from the creation
dialog (or the downloaded JSON) and write `~/.jcode/google_credentials.json`
with owner-only permissions. The secret goes straight from the page to the
file. Never echo it into the transcript.
8. **Run the login.** `jcode login google --google-services gmail,calendar`
(add `--google-access-tier readonly` if the user wants read and draft only).
The user approves the consent screen.
9. **Verify.** Make one read call per granted service (list recent mail, list
upcoming events) and report which services are active.

## What the user must do themselves

- Sign in to Google if needed. The agent never types passwords or 2FA codes.
- Click through the **"Google hasn't verified this app"** screen at login:
Advanced, then "Go to jcode (unsafe)". Warn about this before step 8 and
explain it is expected: it is their own app.
- Approve the consent screen, keeping every requested permission ticked.
Unticked permissions mean that service is not granted (login reports
"Not granted").
- Accept Google Cloud terms of service on first console use.

## Failure handling

| Symptom | Cause | Action |
|---|---|---|
| `access_denied` / "app is blocked" for a Workspace account | Admin blocks unverified third-party apps | Tell the user to ask their admin to allow the client ID, or use a personal account. Do not retry. |
| `Gmail API has not been used in project` / `accessNotConfigured` | API not enabled | Re-open the step 3 link for that service, enable, wait about a minute, retry. |
| `No refresh token received` | Prior grant exists without offline consent | Revoke at `https://myaccount.google.com/permissions`, log in again. |
| Login works, then fails a week later with `invalid_grant` | App left in Testing mode | Publish the app (step 5), log in again. |
| Console UI moved or a selector fails | Google Cloud UI changes | Fall back to the manual instructions in `jcode login google` option [3]. |

## Adding a service later

Re-run `jcode login google --google-services <existing>,<new>`. The login
keeps already-granted services and requests the union of scopes
(`include_granted_scopes=true`). The agent should first enable the new
service's API in the same project (step 3) so the first call does not fail.

## Implementation notes

- The guided flow is agent-driven (browser tool plus shell), not a new
interactive CLI wizard. `jcode login google` keeps its manual paths as the
fallback.
- Tools should return a structured "not configured" message that names the
missing service and suggests guided setup, so the agent can offer it
instead of telling the user to run a CLI command.
- Prerequisite: browser-tool reliability. User reports show intermittent
failures driving Chrome even with the Browser Agent Bridge installed. The
console flow is long and multi-page, so it should only be enabled by
default once browser handoff is dependable.
- Desktop: surface the same flow from the Desktop settings Accounts page,
through the SDK, rather than a Desktop-only implementation.
27 changes: 27 additions & 0 deletions flake.lock

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

43 changes: 43 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
description = "Optional Jcode Rust development environment";

inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";

outputs = { nixpkgs, ... }:
let
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
forAllSystems = nixpkgs.lib.genAttrs systems;
in
{
devShells = forAllSystems (system:
let
pkgs = import nixpkgs { inherit system; };
in
{
default = pkgs.mkShell {
# mkShell supplies the platform C/C++ compiler through stdenv.
packages = with pkgs; [
cargo
rustc
rustfmt
clippy
rust-analyzer
pkg-config
cmake
gnumake
perl
git
ripgrep
];

# macOS voice support generates CoreAudio bindings with libclang.
nativeBuildInputs = pkgs.lib.optionals pkgs.stdenv.isDarwin [
pkgs.rustPlatform.bindgenHook
];

# Native TLS dependencies are used by parts of the provider stack.
buildInputs = [ pkgs.openssl ];
};
});
};
}
1 change: 1 addition & 0 deletions ios/Sources/JCodeMobile/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
Expand Down
63 changes: 63 additions & 0 deletions tests/cli_exit_status.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//! Process-level regressions for clap's CLI exit status and output streams.
use std::process::{Command, Output};

fn invoke(args: &[&str]) -> Output {
let root = tempfile::tempdir().unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_jcode"))
.current_dir(root.path())
.env_clear()
.env("HOME", root.path())
.env("JCODE_HOME", root.path().join("jcode"))
.env("JCODE_NO_TELEMETRY", "1")
.env("NO_COLOR", "1")
.args(args)
.output()
.expect("run jcode CLI");
assert!(
!root.path().join("jcode").exists(),
"parsing must exit before creating application state"
);
output
}

#[test]
fn unknown_subcommand_exits_with_usage_error() {
let output = invoke(&["definitely-not-a-command"]);
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains("unrecognized subcommand 'definitely-not-a-command'"));
assert!(stderr.contains("Usage:"));
}

#[test]
fn unknown_option_exits_with_usage_error() {
let output = invoke(&["--definitely-not-an-option"]);
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains("unexpected argument '--definitely-not-an-option'"));
assert!(stderr.contains("Usage:"));
}

#[test]
fn help_exits_successfully_on_stdout() {
let output = invoke(&["--help"]);
assert_eq!(output.status.code(), Some(0));
assert!(output.stderr.is_empty());
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(stdout.contains("Usage:"));
assert!(stdout.contains("Commands:"));
}

#[test]
fn version_exits_successfully_on_stdout() {
let output = invoke(&["--version"]);
assert_eq!(output.status.code(), Some(0));
assert!(output.stderr.is_empty());
assert!(
String::from_utf8(output.stdout)
.unwrap()
.starts_with("jcode ")
);
}
Loading