Skip to content
Open
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
160 changes: 160 additions & 0 deletions apps/desktop/src/session/events/images.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! Invalidates cached local markdown images in `MdStore` when server events indicate a file on
//! disk changed: exact path invalidation on `filesystem.changed`, `session.step.ended` file lists,
//! and file-targeted tool calls; conditional `ETag` revalidation on `read` hints, arbitrary
//! mutating commands (`bash`, `execute`, etc.), user `!cmd` shell runs (`session.shell.ended`),
//! background shells (`shell.exited`), and reverts.

use opencode_kit::model::{Message, Part};
use serde_json::Value;

use crate::App;

impl App {
/// Marks affected local markdown images stale in response to stream event `ty`.
/// Returns `true` when a visible redraw is needed now.
pub(crate) fn note_markdown_images_event(&self, ty: &str, data: &Value, sid: &str) -> bool {
let md = &self.composer_ext.attach.markdown;
let dir = data["eventLocation"]["directory"]
.as_str()
.filter(|d| !d.is_empty())
.or_else(|| data["location"]["directory"].as_str().filter(|d| !d.is_empty()))
.or_else(|| (!sid.is_empty()).then(|| self.session(sid).map(|i| i.directory.as_str())).flatten())
.filter(|d| !d.is_empty());

match ty {
"filesystem.changed" => {
if let Some(file) = data["file"].as_str().filter(|f| !f.is_empty()) {
md.invalidate_file(dir, file)
} else if let Some(dir) = dir {
md.invalidate_directory(dir)
} else {
false
}
}
"session.tool.success" => self.note_tool_success_images(data, sid, dir),
"session.step.ended" => {
let mut changed = false;
if let Some(files) = data["files"].as_array() {
for file in files.iter().filter_map(Value::as_str) {
changed |= md.invalidate_file(dir, file);
}
}
changed
}
// User `!cmd` runs emit `session.shell.ended` (not `session.execution.succeeded`,
// `packages/core/src/session/session.ts:232-240`); background shells emit `shell.exited`.
"session.shell.ended" | "shell.exited" | "session.revert.committed" => {
if self.shows_transcript(sid) || ty == "shell.exited" {
md.invalidate_all_files()
} else if let Some(dir) = dir {
md.invalidate_directory(dir)
} else {
false
}
}
_ => false,
}
}

fn note_tool_success_images(&self, data: &Value, sid: &str, dir: Option<&str>) -> bool {
let md = &self.composer_ext.attach.markdown;
let (tool_name, tool_input) = self.find_tool_call(sid, data);
let name = tool_name.or_else(|| data["name"].as_str()).unwrap_or("");
let lower = name.to_ascii_lowercase();

if matches!(
lower.as_str(),
"glob" | "grep" | "list" | "ls" | "webfetch" | "websearch" | "todoread" | "skill" | "question"
) {
return false;
}

let mut paths = Vec::new();
collect_metadata_paths(&data["metadata"], &mut paths);
if let Some(input) = tool_input {
collect_input_paths(input, &mut paths);
}

// Read-only hint: keep cached ETag so unchanged images answer 304 Not Modified.
if lower == "read" {
return paths.iter().fold(false, |acc, p| acc | md.revalidate_file(dir, p));
}

let exact_writer = matches!(
lower.as_str(),
"write" | "edit" | "apply_patch" | "patch" | "image_generate" | "image_edit" | "opencode_image_generate" | "opencode_image_edit"
);
if exact_writer && !paths.is_empty() {
return paths.iter().fold(false, |acc, p| acc | md.invalidate_file(dir, p));
}

// Arbitrary commands (`bash`, `execute`, MCP tools, etc.) may overwrite any file on disk;
// mark cached local images stale with their `ETag` intact so unchanged files answer 304.
if self.shows_transcript(sid) {
md.invalidate_all_files()
} else if let Some(dir) = dir {
md.invalidate_directory(dir)
} else {
false
}
}

fn find_tool_call<'a>(&'a self, sid: &str, data: &Value) -> (Option<&'a str>, Option<&'a Value>) {
let Some(id) = data["id"].as_str().filter(|s| !s.is_empty()) else {
return (None, None);
};
let Some(t) = self.transcripts.get(sid) else {
return (None, None);
};
let mid = data["assistantMessageID"].as_str();
for m in t.messages.iter().rev() {
let Message::Assistant(a) = m else { continue };
if let Some(mid) = mid
&& a.id != mid
{
continue;
}
for part in a.parts.iter().rev() {
if let Part::Tool { id: tid, name, input, .. } = part
&& tid == id
{
return (Some(name.as_str()), Some(input));
}
}
if mid.is_some() {
break;
}
}
(None, None)
}
}

fn collect_metadata_paths<'a>(meta: &'a Value, out: &mut Vec<&'a str>) {
if let Some(p) = meta["filediff"]["file"].as_str().filter(|s| !s.is_empty()) {
out.push(p);
}
if let Some(p) = meta["path"].as_str().filter(|s| !s.is_empty()) {
out.push(p);
}
if let Some(files) = meta["files"].as_array() {
for item in files {
if let Some(p) = item
.as_str()
.or_else(|| item["file"].as_str())
.or_else(|| item["filePath"].as_str())
.or_else(|| item["relativePath"].as_str())
.filter(|s| !s.is_empty())
{
out.push(p);
}
}
}
}

fn collect_input_paths<'a>(input: &'a Value, out: &mut Vec<&'a str>) {
for key in ["filePath", "path", "file"] {
if let Some(p) = input[key].as_str().filter(|s| !s.is_empty()) {
out.push(p);
}
}
}
1 change: 1 addition & 0 deletions apps/desktop/src/session/events/incoming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ fn message(s: &mut App, m: Incoming, tx: &mut Tx) -> bool {
// change made meanwhile went unreported.
crate::files::watch::connected(s);
crate::files::watch::reread(s);
s.composer_ext.attach.markdown.invalidate_all_files();
}
// The first open: the link was never down, but the health poll can stand down now.
Incoming::Opened => {
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/session/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use serde_json::Value;

use crate::{App, Route, Source, pickers, servers};

mod images;
pub mod incoming;
pub mod stream;
mod text_block;
Expand Down Expand Up @@ -560,6 +561,7 @@ impl App {
changed |= done.status | self.status_landed(ty, data);
changed |= self.note_review_event(ty, data);
crate::files::watch::on_event(self, ty, data, &sid);
changed |= self.note_markdown_images_event(ty, data, &sid);
if ty.starts_with("pty.") || ty.starts_with("persistent-pty.") {
changed |= self.apply_pty_event(ty, data);
}
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/session/meta/open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ impl App {
}
if *self.route != Route::here(id.to_owned()) {
crate::shell::memory_reclaim::on_tab_switched(self);
self.composer_ext.attach.markdown.invalidate_all_files();
}
*self.route = Route::here(id.to_owned());
crate::narrow::follow_route(self, tx);
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/stories/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub(crate) const ORDER: &[&str] = &[
"Timeline/Subagent starting",
"Timeline/Images",
"Timeline/Image gallery",
"Timeline/Inline image update",
"Timeline/Jump to latest",
"Timeline/Fade into composer",
"Timeline/Scroll bar",
Expand Down
Loading
Loading