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
2 changes: 2 additions & 0 deletions docs/desktop-coding.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ Use unique instance IDs. A JSON entry with the same ID as one of the eight prese
**New worktree** starts a linked worktree from the repository's default branch. Bear uses the cached remote default when available, then looks for `main`, `master`, the checked-out commit, or another available branch. Open **From …** to search local and remote-tracking branches for a different base. Choose **Current checkout** to use the selected folder. Pick a local branch to switch to it when the conversation opens. If Git detects a conflict with local files, the draft stays open so you can change your selection. Repositories without a starting commit use the current checkout.

Type your task and use the send shortcut or click the up arrow. Bear derives a short title from the first message. For example, “Please fix the parser.” becomes **Fix the parser**. A single-repository worktree uses a branch such as `huggler/fix-the-parser` and a checkout folder beginning with `fix-the-parser-`. If the branch name is taken, Bear tries a numbered suffix. The setup view shows the base selection, checkout creation, and conversation opening. Use the model picker at the lower left of the composer to choose a provider and model. **Bear → Create with Setup…** (⌘⇧N) lets you set the conversation title and, for a single-repository worktree, the exact branch name.

Turn on **Generate conversation titles** in **Settings → General** to enable generated titles for new local Codex conversations. The setting applies to new conversations immediately. If you previously set `BEAR_GENERATE_TITLES=1`, Bear uses that value until you change the setting. Bear opens the conversation immediately using the short title it derived locally. In the background, a separate Codex turn uses the first message, project name, and any attachment names to suggest a title. If Codex cannot suggest one, Bear keeps the local title. A title you enter yourself takes precedence. The branch name is set during checkout, before the suggestion arrives.
2. **Send a message.** Press **Enter** to send by default. Use **Shift+Enter** to add a line and **⌘L** to focus the message field. Change the send shortcut under **Settings → General**. In either composer, click **+** or drop files into the composer to attach up to eight files totaling 50 MiB, including up to 20 MiB of images. Click a draft filename to remove it before sending. In history, expand a filename to preview text, images, or extracted PDF text when available. Use **Save as…** to save the original file. You can send files on their own or queue them with a follow-up. The provider receives the filenames and the contents or local file paths supported by that provider. The built-in Codex instance can edit the checkout during implementation. You can change **Model** beside **Message** before sending or queuing your next turn. Bear remembers the selection for this conversation. Read the streaming reply, open command output and respond to questions or permission requests in **Conversation**.
3. **Manage ongoing work.** While the agent works, the send shortcut queues your follow-up by default. Select **Steer** under **Settings → General** to send a text follow-up into a Codex turn that can accept it. **Stop thread** interrupts the current work and pauses queued messages. Use **Resume queue** to deliver them. Choose **Show conversations** in the header to switch to another task. A partially typed answer stays with its question while the app is open. Reopening the app restores the selected conversation and its history.
4. **Review changed files.** The **Changes** tab in the right sidebar defaults to **All changes**, which compares the selected checkout with the branch’s merge base. For a multi-repo workspace, rows include the repository folder and each diff uses its own Git checkout. **All changes** compares each worktree with its starting commit. Choose **Uncommitted files** for staged, unstaged, and untracked files. The line totals follow the selection. Hover over the file name to see its full path. Use the row’s chevron to open **Open in**. Finder reveals the file, Terminal opens its folder, and VS Code opens the file. For deleted files the menu opens the nearest existing folder. Hover over a row with eligible uncommitted edits to show **Revert file**. Confirming a revert restores the path to its state at the current commit and removes files added since then. Resolve conflicts and submodule changes in Git. The list refreshes when you open the sidebar, select a conversation, finish a turn, or revert a file.
Expand Down
9 changes: 7 additions & 2 deletions scripts/check-desktop-history.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,17 @@ def main():
(str(i), thread, i + 1))
db.execute("INSERT INTO message(id,run_id,role,text) VALUES(?,?,'assistant',?)",
(str(i), str(i), long_message if i == 998 else f"Answer {i}"))
db.execute("UPDATE run SET status='failed', error=? WHERE id='999'",
db.execute("UPDATE run SET status='failed', error=?, ordinal=1002 WHERE id='999'",
("Provider could not finish this turn.",))
db.execute("INSERT INTO run(id,thread_id,status,ordinal) VALUES('canceled',?,'interrupted',1001)",
(thread,))
db.execute("INSERT INTO message(id,run_id,role,text) VALUES('canceled','canceled','user',?)",
("Canceled before delivery",))
error_response = "error/Provider could not finish this turn."
steps = [
{"see": error_response},
{"see": "Codex/Answer 999"}, {"absent": "Codex/Answer 967"}, {"see": "active-turn/32"},
{"see": "Codex/Answer 999"}, {"absent": "You/Canceled before delivery"},
{"see": "Codex/Answer 968"}, {"absent": "Codex/Answer 967"}, {"see": "active-turn/32"},
{"click": "Older"}, {"see": "Codex/Answer 967"}, {"absent": "Codex/Answer 999"},
{"absent": error_response},
{"see": "active-turn/1"}, {"see": "Newest"}, {"click": "Scroll to end"},
Expand Down
39 changes: 39 additions & 0 deletions scripts/check-desktop-settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,44 @@ def check_general(executable, state, env):
], env)


def check_generated_titles(executable, state, env):
env = dict(env, BEAR_GENERATE_TITLES="0",
HUGGLER_CODEX=str(ROOT / "tests/fixtures/context-provider.py"))
toggle_titles = [
{"key": "cmd-,"}, {"click": "General"}, {"click": "Generate conversation titles"},
{"click": "Back to Settings"}, {"click": "Back to workspace"},
]
prefs = state / "preferences.json"
run_window(executable, state, [
{"resize": [640, 440]}, *toggle_titles,
], env)
assert json.loads(prefs.read_text())["generateConversationTitles"] is True
run_window(executable, state, [
{"resize": [1120, 740]},
{"click": "First message"}, {"type": "Please investigate why the upload stalls."},
{"click": "Send first message"}, {"see": "thread/Upload stall investigation"},
{"contains": "Codex/reply"},
{"key": "cmd-n"}, {"click": "First message"}, {"type": "Keep my chosen conversation title."},
{"key": "cmd-shift-n"}, {"click": "Conversation name"}, {"type": "My title"},
{"click": "Send first message"}, {"see": "thread/My title"}, {"contains": "Codex/reply"},
], env)
run_window(executable, state, [
*toggle_titles,
{"key": "cmd-n"}, {"click": "First message"}, {"type": "Please investigate why the upload stalls."},
{"click": "Send first message"}, {"see": "thread/Investigate why the upload stalls"},
{"contains": "Codex/reply"},
], dict(env, BEAR_GENERATE_TITLES="1"))
assert json.loads(prefs.read_text())["generateConversationTitles"] is False
with sqlite3.connect(state / "huggler.sqlite3") as db:
assert db.execute("SELECT name FROM thread ORDER BY rowid").fetchall() == [
("Upload stall investigation",), ("My title",), ("Investigate why the upload stalls",),
]
frames = (json.loads(line) for log in state.rglob("frames.ndjson")
for line in log.read_text().splitlines())
assert sum((frame.get("params", {}).get("outputSchema") or {}).get("required") == ["title"]
for frame in frames) == 1


def check_worktrees(executable, state, env):
run_window(executable, state, [
{"resize": [640, 440]}, {"key": "cmd-,"}, {"center_x": ["Appearance", 320]},
Expand Down Expand Up @@ -478,6 +516,7 @@ def check(executable):
exclude.write("\n/frames.ndjson\n")
env = dict(isolated_env(root), HUGGLER_CLAUDE_ACP=str(root / "missing-claude-agent"))
check_general(executable, root / "general", env)
check_generated_titles(executable, root / "generated-titles", env)
check_worktrees(executable, root / "worktrees", env)
check_projects(executable, root / "projects", env)
check_provider_setup(executable, root, env)
Expand Down
70 changes: 60 additions & 10 deletions src/conversation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ use huggler::{
use std::{
collections::{HashMap, HashSet},
fs,
path::PathBuf,
path::{Path, PathBuf},
sync::Arc,
};
use uuid::Uuid;
Expand Down Expand Up @@ -1012,7 +1012,8 @@ impl Desktop {
let message = self.starter.read(cx).value().to_string();
let name = self.name.read(cx).value();
let name = name.trim();
let name = if name.is_empty() {
let derive_title = name.is_empty();
let name = if derive_title {
self.starter_attachments.title(&message)
} else {
name.to_owned()
Expand All @@ -1033,6 +1034,7 @@ impl Desktop {
let (model, options) = self.launch_model_selection(cx);
LaunchDraft {
name,
derive_title,
message,
project_name: self.launch_project_name(cx),
checkout,
Expand Down Expand Up @@ -1079,6 +1081,8 @@ impl Desktop {
) {
let LaunchDraft {
name,
derive_title,
project_name,
message,
checkout,
checkout_root,
Expand All @@ -1089,7 +1093,6 @@ impl Desktop {
model,
model_options,
instance,
..
} = draft;
let saved_roots: HashSet<_> = self
.settings
Expand Down Expand Up @@ -1130,22 +1133,68 @@ impl Desktop {
}
let launch_name = name.clone();
let (report_stage, mut stages) = tokio::sync::mpsc::unbounded_channel();
let title_provider = (derive_title
&& self
.settings
.read(cx)
.preferences()
.generates_conversation_titles())
.then(|| {
runtime
.provider_instances()
.find(|provider| provider.id == instance && provider.driver == Provider::Codex)
.cloned()
})
.flatten();
let executor = self.executor.clone();
let launch = cx.background_spawn(async move {
let send = || match first_message {
Some(action) => runtime.dispatch(Command {
let generate_title = title_provider.is_some();
let send = |checkout: Option<&Path>| -> huggler::Result<()> {
let Some(action) = first_message else {
return Ok(());
};
let title_job = title_provider.zip(checkout).and_then(|(provider, checkout)| {
let expected = runtime.thread_title(&thread).ok()?;
if expected.as_str() != name {
return None;
}
let context = launch_workspace::title_context(&action)?;
Some((provider, checkout.to_owned(), expected, context))
});
runtime.dispatch(Command {
id: CommandId(saved_draft.map_or_else(
|| Uuid::new_v4().to_string(),
|id| format!("backlog-send-{id}"),
)),
thread_id: thread.clone(),
action,
}).map(|_| ()),
None => Ok(()),
})?;
if let Some((provider, checkout, expected, context)) = title_job {
let runtime = runtime.clone();
executor.spawn(async move {
launch_workspace::generate_title(
&runtime, provider, checkout, expected, context, project_name,
)
.await;
});
}
Ok(())
};
// Launch and enqueue commit separately. A retry uses the existing
// conversation and the same enqueue ID, even after an app restart.
if saved_draft.is_some() && backlog::has_draft_conversation(&runtime, &thread)? {
return Ok((send(), None, None));
// A previously accepted enqueue can replay its receipt. Only
// generate here if the first enqueue never created a run.
let checkout = if generate_title
&& runtime
.detail(&thread, None, "", 1)
.is_ok_and(|detail| detail.latest_run.is_none())
{
runtime.thread_checkout(&thread).ok()
} else {
None
};
return Ok((send(checkout.as_deref()), None, None));
}
if saved_draft.is_some() && workspace_mode == WorkspaceMode::Worktree {
let _ = report_stage.send(Some(WorktreeStage::ResolveBase));
Expand Down Expand Up @@ -1183,7 +1232,7 @@ impl Desktop {
return Err(workspace.cleanup(error.into()));
}
return Ok((
send(),
send(Some(&workspace.project.root)),
Some((workspace.project.root, primary.clone())),
None,
));
Expand Down Expand Up @@ -1239,14 +1288,15 @@ impl Desktop {
error
});
}
let sent = send(Some(&project.root));
// A saved linked checkout can define its own actions. Git only reports
// the repository's main checkout from the newly allocated worktree.
let worktree_project = (allocated
&& saved_roots.contains(&source_root)
&& git::main_worktree(&project.root).is_ok_and(|main| main != source_root))
.then_some((project.root, source_root));
let history_error = setup_record.and_then(Result::err);
anyhow::Ok((send(), worktree_project, history_error))
anyhow::Ok((sent, worktree_project, history_error))
});
cx.spawn_in(window, async move |view, cx| {
while let Some(stage) = stages.recv().await {
Expand Down
3 changes: 3 additions & 0 deletions src/conversation/backlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use std::{
#[derive(Serialize, Deserialize)]
pub(super) struct LaunchDraft {
pub name: String,
#[serde(default)]
pub derive_title: bool,
pub message: String,
pub checkout: PathBuf,
#[serde(default)]
Expand Down Expand Up @@ -397,6 +399,7 @@ impl Desktop {
!message.trim().is_empty() || !attachments.is_empty(&message),
"Add a message or keep an attachment"
);
launch.derive_title = name.is_empty() || (launch.derive_title && name == launch.name);
launch.name = if name.is_empty() {
attachments.title(&message)
} else {
Expand Down
46 changes: 46 additions & 0 deletions src/conversation/launch_workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,52 @@ pub(super) fn worktree_setup(current: WorktreeStage, title: Option<&str>, cx: &A
}))
}

pub(super) fn title_context(action: &Action) -> Option<String> {
match action {
Action::Enqueue { text } => Some(text.clone()),
Action::EnqueueFiles { text, files } => {
let names = files
.iter()
.map(|file| file.name.as_str())
.collect::<Vec<_>>();
Some(format!("{text}\n\nAttachments: {}", names.join(", ")))
}
_ => None,
}
}

pub(super) async fn generate_title(
runtime: &Huggler,
provider: huggler::ProviderInstance,
checkout: PathBuf,
expected: huggler::ThreadTitle,
context: String,
project_name: Option<String>,
) {
let request = huggler::ConversationTitleRequest {
context: &context,
project_title: project_name.as_deref(),
..Default::default()
};
let result = huggler::providers::codex::generate_conversation_title(
&provider,
runtime.output(),
&checkout,
None,
request,
)
.await
.and_then(|title| {
if let Some(title) = title {
runtime.set_thread_title_if_current(&expected, &title)?;
}
Ok(())
});
if let Err(error) = result {
eprintln!("Could not generate conversation title: {error}");
}
}

pub(super) fn conversation_title(message: &str, attachment: Option<&str>) -> String {
fn append_inline_text(node: &Node, text: &mut String) {
match node {
Expand Down
Loading
Loading