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
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ Zcode 会话读取不意味着其 ACP 运行时、设置、Skill、MCP 或 Hook
下一次目录扫描时重新计算,保留最近本地工作区及同根登记顺序的匹配规则。启动仅将会话标题、来源和归属写入集中会话目录的
`.external-session-index.json`;该私有索引由现有持久化入口合并到元数据分页,旧主机忽略此文件,
既有原生 Session 格式不变。改名、归档和删除只更新索引;删除保留抑制记录,重新扫描不复活条目。
来源开关开启时,每次展开工作区会话列表检查一次外部来源;保持展开、窗口恢复可见和时间流逝均不触发重复扫描。
首屏仍由现有启动调度器加载,检查使用元数据分页请求的可选 `refresh_external_discovery`,由主机强制刷新已完成的发现结果。
正在扫描时复用同一任务,请求通过完成通知等待结果,并以 `discoveryRefreshed` 确认完成,不定时查询扫描进度。
目录修订未变化时不刷新导航;发现新会话后重新读取可见页。全部关闭来源时不因展开而检查。
开关变更按设备、激活版本和工作区记录处理进度,成功后不重复消费;失败或取消仍可重试。旧主机缺少完成确认时报告刷新失败,不把旧目录误判为本次扫描结果。
会话元数据分页通过可选 `query` 声明工作区 ID、创建/最近活动排序、来源及已观察到的活动时间,
主机完成归属筛选、父子分组和来源筛选后返回分页与精确计数,并以 `catalogQuery` 回显已应用条件。
Web UI 默认仅读取可见页,展开时续读,复用启动首屏;相同时间的边界条目一起返回,保留客户端的本地化排序。
Expand Down
11 changes: 11 additions & 0 deletions src/apps/cli/src/peer_host/commands/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,16 @@ pub(crate) async fn list_persisted_sessions_page(
.transpose()
.map_err(|error| format!("Invalid session activity ids: {error}"))?;
let query = session_catalog_query(request)?;
let refresh_external_discovery = request
.get("refresh_external_discovery")
.or_else(|| request.get("refreshExternalDiscovery"))
.map(|value| {
value
.as_bool()
.ok_or("Invalid external discovery refresh flag")
})
.transpose()?
.unwrap_or(false);
let page = state
.compatibility
.list_persisted_sessions_page_with_activity_and_query(
Expand All @@ -327,6 +337,7 @@ pub(crate) async fn list_persisted_sessions_page(
limit,
session_ids.as_deref(),
query.as_ref(),
refresh_external_discovery,
)
.await
.map_err(|e| format!("Failed to list persisted session page: {e}"))?;
Expand Down
8 changes: 8 additions & 0 deletions src/apps/desktop/src/api/session_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ pub struct ListPersistedSessionsPageRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<openbitfun_services_core::session::page::SessionCatalogQuery>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_external_discovery: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_connection_id: Option<String>,
Expand Down Expand Up @@ -465,6 +467,7 @@ pub async fn list_persisted_sessions_page(
request.limit,
request.session_ids.as_deref(),
request.query.as_ref(),
request.refresh_external_discovery.unwrap_or(false),
)
.await
.map_err(|error| {
Expand Down Expand Up @@ -938,5 +941,10 @@ mod catalog_request_tests {
serde_json::from_value(current.clone()).unwrap();
assert_eq!(request.query.as_ref().unwrap().workspace_id, "main");
assert_eq!(serde_json::to_value(request).unwrap(), current);
current["refresh_external_discovery"] = serde_json::json!(true);
let request: ListPersistedSessionsPageRequest =
serde_json::from_value(current.clone()).unwrap();
assert_eq!(request.refresh_external_discovery, Some(true));
assert_eq!(serde_json::to_value(request).unwrap(), current);
}
}
2 changes: 2 additions & 0 deletions src/apps/desktop/src/runtime/session_application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ impl DesktopSessionApplication {
limit: usize,
session_ids: Option<&[String]>,
query: Option<&openbitfun_services_core::session::page::SessionCatalogQuery>,
refresh_external_discovery: bool,
) -> DesktopSessionApplicationResult<SessionMetadataPage> {
let scope = self.resolved_scope(request).await?;
let storage_path = self.storage_path(&scope);
Expand All @@ -405,6 +406,7 @@ impl DesktopSessionApplication {
limit,
session_ids,
query.filter(|query| query.workspace_id == scope.workspace_id),
refresh_external_discovery,
)
.await
.map_err(|error| DesktopSessionApplicationError::Core(error.to_string()))?;
Expand Down
19 changes: 17 additions & 2 deletions src/crates/assembly/core/src/agentic/persistence/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8411,6 +8411,7 @@ mod tests {
workspace_id: "main".into(),
ordering: SessionCatalogOrdering::Created,
source: "all".into(),
sources: Vec::new(),
sort_timestamps: Default::default(),
};
let first = manager
Expand Down Expand Up @@ -8494,12 +8495,26 @@ mod tests {
.unwrap();
assert!(filtered.catalog_reset);
assert_eq!(filtered.total_top_level_count, 0);
let mut changed_allowlist = query.clone();
changed_allowlist.sources = vec!["openbitfun".into()];
let allowlisted = manager
.list_session_metadata_page_with_query(
workspace.path(),
second.next_cursor.as_deref(),
5,
Some(&changed_allowlist),
)
.await
.unwrap();
assert!(allowlisted.catalog_reset);
assert_eq!(allowlisted.total_top_level_count, 12);
assert_ne!(allowlisted.catalog_revision, first.catalog_revision);
let replay = manager
.list_session_metadata_page_with_query(workspace.path(), None, 5, Some(&query))
.await
.unwrap();
assert_eq!(replay.catalog_revision, refreshed.catalog_revision);
assert_eq!(manager.session_catalog_build_count_for_test().await, 3);
assert_eq!(manager.session_catalog_build_count_for_test().await, 4);

// A deleted selected entry still triggers the existing index repair.
std::fs::remove_file(
Expand All @@ -8514,7 +8529,7 @@ mod tests {
.unwrap();
assert_eq!(repaired.total_top_level_count, 11);
assert_eq!(repaired.sessions[0].session_id, "catalog-10");
assert_eq!(manager.session_catalog_build_count_for_test().await, 4);
assert_eq!(manager.session_catalog_build_count_for_test().await, 5);
}

#[tokio::test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ impl CatalogRevision {
}

fn cursor_revision(&self, root: &Path, query: &SessionCatalogQuery) -> String {
let mut sources = query.sources.iter().collect::<Vec<_>>();
sources.sort_unstable();
let mut sort_timestamps = query.sort_timestamps.iter().collect::<Vec<_>>();
sort_timestamps.sort_unstable_by(|left, right| left.0.cmp(right.0));
let mut hash = Sha256::new();
Expand All @@ -45,6 +47,7 @@ impl CatalogRevision {
&query.workspace_id,
query.ordering,
&query.source,
sources,
sort_timestamps,
))
.expect("catalog query is serializable"),
Expand Down
124 changes: 121 additions & 3 deletions src/crates/assembly/core/src/external_session_import/auto_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use openbitfun_services_core::session::SessionDiscoveryDiagnostic;
struct DiscoveryState {
enabled_sources: Option<Vec<String>>,
activation_revision: Option<i64>,
changed: Arc<tokio::sync::Notify>,
snapshot: DiscoverySnapshot,
cancelled: Arc<AtomicBool>,
worker: Arc<tokio::sync::Mutex<()>>,
Expand Down Expand Up @@ -57,8 +58,8 @@ async fn enabled_sources() -> Result<Vec<String>, String> {
}

/// Opening a workspace explicitly refreshes discovery. Metadata reads also run
/// this once after startup (including restored background workspace rows), and
/// after the user changes a source toggle. Concurrent readers share one scan.
/// this once after startup and source-toggle changes. Explicit reveals refresh
/// a completed snapshot; concurrent readers share a running scan.
pub async fn discover_workspace(workspace: &WorkspaceInfo, refresh: bool) -> DiscoverySnapshot {
let enabled = match enabled_sources().await {
Ok(enabled) => enabled,
Expand Down Expand Up @@ -124,6 +125,7 @@ where
state.enabled_sources = Some(enabled);
state.activation_revision = activation_revision;
state.snapshot = DiscoverySnapshot::default();
state.changed.notify_waiters();
return state.snapshot.clone();
}
if state.enabled_sources.as_ref() == Some(&enabled)
Expand Down Expand Up @@ -159,6 +161,7 @@ where
warnings: result.warnings,
diagnostics: result.diagnostics,
};
state.changed.notify_waiters();
}
});
state.snapshot.clone()
Expand All @@ -168,6 +171,16 @@ where
/// remote workspace's synthetic local storage directory is never treated as a
/// source directory and cannot cause a scan of controller-side history.
pub async fn discover_for_storage_path(storage_path: &Path) -> DiscoverySnapshot {
discovery_for_storage_path(storage_path, false).await
}

/// A user reveal performs one refresh and waits for host-owned work. Completion
/// wakes the request through a notification, never through timed status reads.
pub async fn refresh_for_storage_path(storage_path: &Path) -> DiscoverySnapshot {
discovery_for_storage_path(storage_path, true).await
}

async fn discovery_for_storage_path(storage_path: &Path, refresh: bool) -> DiscoverySnapshot {
let Some(service) = crate::service::workspace::get_global_workspace_service() else {
return DiscoverySnapshot::default();
};
Expand All @@ -176,7 +189,11 @@ pub async fn discover_for_storage_path(storage_path: &Path) -> DiscoverySnapshot
crate::service::WorkspaceRuntimeService::new(crate::infrastructure::get_path_manager_arc());
let mut snapshot = DiscoverySnapshot::default();
for workspace in workspaces_for_storage_path(storage_path, &workspaces, &runtime) {
let discovery = discover_workspace(workspace, false).await;
let mut discovery = discover_workspace(workspace, refresh).await;
if refresh && discovery.pending {
let key = format!("{}:{}", workspace.id, normalized_path(&workspace.root_path));
discovery = wait_for_discovery(&key).await;
}
snapshot.pending |= discovery.pending;
snapshot.warnings.extend(discovery.warnings);
snapshot.diagnostics.extend(discovery.diagnostics);
Expand All @@ -194,6 +211,27 @@ pub async fn discover_for_storage_path(storage_path: &Path) -> DiscoverySnapshot
snapshot
}

async fn wait_for_discovery(key: &str) -> DiscoverySnapshot {
let lock = DISCOVERY
.lock()
.unwrap_or_else(|error| error.into_inner())
.get(key)
.expect("pending discovery has a state")
.clone();
let changed = lock.lock().await.changed.clone();
loop {
let notified = changed.notified();
tokio::pin!(notified);
notified.as_mut().enable();
let state = lock.lock().await;
if !state.snapshot.pending {
return state.snapshot.clone();
}
drop(state);
notified.await;
}
}

fn workspaces_for_storage_path<'a>(
storage_path: &Path,
workspaces: &'a [WorkspaceInfo],
Expand Down Expand Up @@ -569,6 +607,86 @@ pub(super) mod tests {
assert_eq!(final_snapshot.warnings, vec!["fixture warning"]);
}

#[tokio::test]
async fn explicit_refresh_waits_for_notification_and_rescans_completed_work() {
let key = Uuid::new_v4().to_string();
let (release, wait) = tokio::sync::oneshot::channel();
schedule_discovery(
key.clone(),
vec!["codex".into()],
false,
None,
|_| async move {
wait.await.unwrap();
DiscoveryResult {
warnings: vec!["original catalog".into()],
..Default::default()
}
},
)
.await;
let waiter_key = key.clone();
let waiter = tokio::spawn(async move { wait_for_discovery(&waiter_key).await });
tokio::task::yield_now().await;
assert!(!waiter.is_finished());
let shared = schedule_discovery(key.clone(), vec!["codex".into()], true, None, |_| async {
panic!("A reveal must share the existing worker")
})
.await;
assert!(shared.pending);
release.send(()).unwrap();
let completed = tokio::time::timeout(Duration::from_secs(2), waiter)
.await
.unwrap()
.unwrap();
assert!(!completed.pending);
assert_eq!(completed.warnings, vec!["original catalog"]);
// A completion before subscription must also return immediately.
assert!(!wait_for_discovery(&key).await.pending);
schedule_discovery(key.clone(), vec!["codex".into()], true, None, |_| async {
DiscoveryResult {
warnings: vec!["new session catalog".into()],
..Default::default()
}
})
.await;
let refreshed = tokio::time::timeout(Duration::from_secs(2), wait_for_discovery(&key))
.await
.unwrap();
assert_eq!(refreshed.warnings, vec!["new session catalog"]);
}

#[tokio::test]
async fn disabling_sources_wakes_an_explicit_refresh_waiter() {
let key = Uuid::new_v4().to_string();
let (release, wait) = tokio::sync::oneshot::channel();
schedule_discovery(
key.clone(),
vec!["codex".into()],
false,
None,
|_| async move {
let _ = wait.await;
DiscoveryResult::default()
},
)
.await;
let waiter_key = key.clone();
let waiter = tokio::spawn(async move { wait_for_discovery(&waiter_key).await });
tokio::task::yield_now().await;
schedule_discovery(key, vec![], false, None, |_| async {
panic!("Disabled sources must not be scanned")
})
.await;
let disabled = tokio::time::timeout(Duration::from_secs(2), waiter)
.await
.unwrap()
.unwrap();
assert!(!disabled.pending);
assert!(disabled.warnings.is_empty());
let _ = release.send(());
}

#[tokio::test]
async fn disabling_discovery_cancels_pending_work_without_retaining_stale_issues() {
let key = Uuid::new_v4().to_string();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1607,6 +1607,7 @@ mod tests {
workspace_id: workspace.id.clone(),
ordering: SessionCatalogOrdering::Updated,
source: "codex".into(),
sources: Vec::new(),
sort_timestamps: HashMap::new(),
};
let first = manager
Expand Down Expand Up @@ -2056,6 +2057,7 @@ mod tests {
workspace_id: workspace.id.clone(),
ordering: openbitfun_services_core::session::page::SessionCatalogOrdering::Updated,
source: "all".into(),
sources: Vec::new(),
sort_timestamps: HashMap::new(),
};
let fallback = manager
Expand Down
Loading
Loading