v0.8.9: sessions in the Qt front end, transcript replay, UI test helpers

A conversation is now something the window can pick. The sidebar lists the
workspace's stored sessions and switching replays one into the view.

Sessions (app/src/core/AgentCore.*, app/qml/SessionRow.qml, Sidebar.qml):
- AgentCore::open() resolves the workspace's current session through
  cst_agent_store_resolve_default() before the engine starts. Without it the
  engine opened session.jsonl in the process's working directory, next to a
  session list that stayed empty.
- sessionId property; sessions() (id, title, firstUser, messages, mtime in ms,
  current); newSession(), switchSession(), deleteSession() (moves the engine
  off a session it has open first), renameSession(); sessionChanged and
  sessionListChanged signals. No mutation runs during a turn.
- history() turns the open session back into the rows the live signals build
  (kind/role/text/name/state/detail/output/exitCode/complete): system prompt
  skipped, notes and attachments shown, assistant reasoning as a think row,
  tool_calls_json as one card per call, and each result paired with its call
  the way findTool() pairs the live stream. A call with no result keeps state
  "unfinished" ("no result"), so a replay never shows a spinner that cannot
  stop. Main.qml replays on sessionChanged.
- SessionRow.qml is a file of its own: as an inline component it would not see
  the Repeater's modelData. Session controls are disabled while a turn runs.

Tests (app/src/ui/UiTest.cpp, app/src/main.cpp):
- the fixture session is written through the store's own API (a tool call with
  its result), then the checks click its row, assert the five replayed rows and
  the paired result, start two new sessions (the view empties), delete one by
  its button (the open one stays), and switch back. 28 checks in total.
- item() falls back to the visual tree: delegates a model owns are not always
  in the window's QObject tree, which is why the rows were invisible to
  findChild even though they were on screen.
- --uitest drives a scratch workspace unless --workspace is given; it creates
  and deletes sessions. CST_APP_SHOT=file saves the window as a PNG when the
  run ends and CST_APP_DUMP=1 prints the session rows seen; both are how the
  layout gets looked at on a machine without a screen.

QML: ThinkBlock's click target is a TapHandler on its row (a MouseArea anchored
inside a layout is undefined behavior and Qt said so).

Verified: 28/28 UI checks, --selftest, ctest cst-app-selftest, make check rc=0,
and a screenshot of a replayed session (cards, tool card with its result, the
think block, the sidebar list).

Version 0.8.9.
This commit is contained in:
WHC
2026-10-11 12:14:59 +08:00
parent da812cc7e8
commit f5d340bd2a
13 changed files with 691 additions and 13 deletions
+238
View File
@@ -3,7 +3,12 @@
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringList>
#include <QThread>
#include <QVariantMap>
#include <cstdlib>
@@ -71,6 +76,14 @@ bool AgentCore::open(const QString &workspace, const QString &provider,
if (!apiKey.isEmpty())
snprintf(m_cfg.api_key, sizeof(m_cfg.api_key), "%s",
apiKey.toUtf8().constData());
/* Sessions live in the workspace's store -- the same files the CLI and the
* WebUI use. Without this the engine would open session.jsonl in the
* process's working directory, next to a session list that stays empty. */
char sid[128] = "";
if (cst_agent_store_resolve_default(m_cfg.workspace_root, m_cfg.session_path,
sizeof(m_cfg.session_path), sid,
sizeof(sid)) != 0)
m_cfg.session_path[0] = 0; /* fall back to the engine's default */
/* The GUI answers itself: never let the engine decide behind its back. */
m_cfg.auto_approve = 0;
m_cfg.headless = 0;
@@ -243,6 +256,231 @@ void AgentCore::setPlanMode(bool on) {
emit planModeChanged();
}
/* --- sessions ------------------------------------------------------------ */
namespace {
QString utf8(const char *s) { return QString::fromUtf8(s ? s : ""); }
/* A transcript row in the shape Main.qml appends live (see addRow()). */
QVariantMap sessionRow(const QString &kind, const QString &role) {
QVariantMap r;
r["kind"] = kind;
r["role"] = role;
r["text"] = QString();
r["complete"] = false;
r["name"] = QString();
r["state"] = QString();
r["detail"] = QString();
r["output"] = QString();
r["exitCode"] = 0;
return r;
}
/* The last tool row with this name that is still open, -1 when none: the
* pairing findTool() does for the live stream, so a replayed result lands on
* the card of its own call. An unmatched call keeps state "unfinished": an
* interrupted turn should not show a spinner that will never stop. */
int findOpenTool(const QVariantList &rows, const QString &name) {
for (int i = rows.size() - 1; i >= 0; i--) {
const QVariantMap r = rows.at(i).toMap();
if (r.value(QStringLiteral("kind")).toString() != QLatin1String("tool"))
continue;
if (r.value(QStringLiteral("complete")).toBool())
return -1;
if (r.value(QStringLiteral("name")).toString() == name)
return i;
}
return -1;
}
} // namespace
QString AgentCore::sessionId() const {
if (!m_agent)
return QString();
char id[128] = "";
cst_agent_session_id(m_agent, id, sizeof(id));
return utf8(id);
}
QVariantList AgentCore::sessions() const {
QVariantList out;
if (m_workspace.isEmpty())
return out;
const QByteArray ws = m_workspace.toUtf8();
const int kMax = 200;
char(*ids)[128] = new char[kMax][128];
const int n = cst_agent_store_list(ws.constData(), ids, kMax);
const QString current = sessionId();
for (int i = 0; i < n; i++) {
cst_session_info_t in;
memset(&in, 0, sizeof(in));
if (cst_agent_store_info(ws.constData(), ids[i], &in) != 0)
continue;
const QString id = utf8(in.id[0] ? in.id : ids[i]);
QVariantMap m;
m["id"] = id;
m["title"] = utf8(in.title);
m["firstUser"] = utf8(in.first_user);
m["messages"] = in.messages;
m["mtime"] = static_cast<qlonglong>(in.mtime) * 1000; /* ms, for JS Date */
m["current"] = (id == current);
out.append(m);
}
delete[] ids;
return out;
}
QVariantList AgentCore::history() const {
QVariantList rows;
cst_session_t *s = m_agent ? cst_agent_session(m_agent) : nullptr;
if (!s)
return rows;
cst_session_lock(s);
const int n = cst_session_count(s);
for (int i = 0; i < n; i++) {
const cst_message_t *m = cst_session_get(s, i);
if (!m || m->role == CST_ROLE_SYSTEM)
continue; /* the prompt is the engine's, not the conversation */
if (m->role == CST_ROLE_TOOL || cst_message_is_tool_result(m)) {
/* Tool output: role=tool in the native protocol, a user message in the
* text ones. Both belong on the card of the call they answer. */
const QString name = utf8(m->tool_name);
const int at = findOpenTool(rows, name);
if (at < 0) {
QVariantMap r = sessionRow(QStringLiteral("tool"), QStringLiteral("tool"));
r["name"] = name;
r["output"] = utf8(m->content);
r["state"] = "done";
r["complete"] = true;
rows.append(r);
} else {
QVariantMap r = rows.at(at).toMap();
r["output"] = utf8(m->content);
r["state"] = "done";
r["complete"] = true;
rows[at] = r;
}
continue;
}
if (cst_message_is_note(m)) {
QVariantMap r = sessionRow(QStringLiteral("note"), QStringLiteral("engine"));
r["text"] = utf8(m->content);
r["complete"] = true;
rows.append(r);
continue;
}
if (m->role == CST_ROLE_USER) {
QVariantMap r = sessionRow(QStringLiteral("message"), QStringLiteral("user"));
QString text = utf8(m->content);
if (m->nattach > 0) {
QStringList names;
for (int a = 0; a < m->nattach; a++)
names << utf8(m->attach[a].name);
text += QStringLiteral("\n\n[attached: %1]").arg(names.join(", "));
}
r["text"] = text;
r["complete"] = true;
rows.append(r);
continue;
}
if (m->role != CST_ROLE_ASSISTANT)
continue;
if (m->reasoning && m->reasoning[0]) {
QVariantMap r = sessionRow(QStringLiteral("think"), QStringLiteral("agent"));
r["text"] = utf8(m->reasoning);
r["complete"] = true;
rows.append(r);
}
if (m->content && m->content[0]) {
QVariantMap r = sessionRow(QStringLiteral("message"), QStringLiteral("agent"));
r["text"] = utf8(m->content);
r["complete"] = true;
rows.append(r);
}
if (m->tool_calls_json) {
const QJsonArray calls =
QJsonDocument::fromJson(QByteArray(m->tool_calls_json)).array();
for (const QJsonValue &v : calls) {
const QJsonObject fn = v.toObject().value(QStringLiteral("function")).toObject();
QVariantMap r = sessionRow(QStringLiteral("tool"), QStringLiteral("tool"));
r["name"] = fn.value(QStringLiteral("name")).toString();
r["detail"] = fn.value(QStringLiteral("arguments")).toString();
r["state"] = "unfinished"; /* until its result shows up below */
rows.append(r);
}
}
}
cst_session_unlock(s);
return rows;
}
void AgentCore::afterSessionChange() {
const QString todo = utf8(cst_agent_todo(m_agent));
emit sessionChanged();
emit sessionListChanged();
if (todo != m_todo) {
m_todo = todo;
emit todoChanged(todo);
}
}
bool AgentCore::newSession() {
if (!m_agent || m_running)
return false;
char id[128] = "";
if (cst_agent_new_session(m_agent, id, sizeof(id)) != 0)
return false;
afterSessionChange();
return true;
}
bool AgentCore::switchSession(const QString &id) {
if (!m_agent || m_running || id.isEmpty())
return false;
if (id == sessionId())
return true;
if (cst_agent_switch_session(m_agent, id.toUtf8().constData()) != 0)
return false;
afterSessionChange();
return true;
}
bool AgentCore::deleteSession(const QString &id) {
if (!m_agent || m_running || id.isEmpty() || m_workspace.isEmpty())
return false;
const bool wasOpen = (id == sessionId());
if (wasOpen) {
/* The engine must not sit on a transcript that is about to vanish: it
* moves to a fresh session first, exactly like the WebUI does. */
char fresh[128] = "";
if (cst_agent_new_session(m_agent, fresh, sizeof(fresh)) != 0)
return false;
}
const QByteArray ws = m_workspace.toUtf8();
const QByteArray sid = id.toUtf8();
if (cst_agent_store_delete(ws.constData(), sid.constData()) != 0)
return false;
if (wasOpen)
afterSessionChange();
else
emit sessionListChanged();
return true;
}
bool AgentCore::renameSession(const QString &id, const QString &title) {
if (id.isEmpty() || m_workspace.isEmpty())
return false;
const QByteArray ws = m_workspace.toUtf8(), sid = id.toUtf8(),
t = title.toUtf8();
if (cst_agent_store_title_set(ws.constData(), sid.constData(), t.constData()) !=
0)
return false;
emit sessionListChanged();
return true;
}
/* --- tools the front end provides ---------------------------------------- */
bool AgentCore::registerTool(const cst_tool_def_t *def) {
+22
View File
@@ -12,6 +12,7 @@
#include <QMutex>
#include <QObject>
#include <QString>
#include <QVariantList>
#include <QWaitCondition>
#include "cst_agent.h"
@@ -29,6 +30,7 @@ class AgentCore : public QObject {
Q_PROPERTY(int approval READ approval WRITE setApproval NOTIFY approvalChanged)
Q_PROPERTY(bool planMode READ planMode WRITE setPlanMode NOTIFY planModeChanged)
Q_PROPERTY(QString todo READ todo NOTIFY todoChanged)
Q_PROPERTY(QString sessionId READ sessionId NOTIFY sessionChanged)
public:
explicit AgentCore(QObject *parent = nullptr);
@@ -48,11 +50,27 @@ class AgentCore : public QObject {
int approval() const { return m_cfg.approval; }
bool planMode() const { return m_cfg.plan_mode != 0; }
QString todo() const { return m_todo; }
QString sessionId() const;
/* Markdown -> HTML with the engine's own renderer (cst_web_md_html), so a
* message looks the same here as it does in the WebUI. */
Q_INVOKABLE QString renderMarkdown(const QString &text) const;
/* --- sessions (the workspace's .agent/sessions store) ------------------- */
/* Stored sessions, newest first; one map each: id, title (a rename, else
* empty), firstUser, messages, mtime (ms since the epoch), current. */
Q_INVOKABLE QVariantList sessions() const;
/* The open session as transcript rows, in exactly the shape the live
* signals build (kind, role, text, name, state, detail, output, exitCode,
* complete), so a reopened session renders like the turn that wrote it. */
Q_INVOKABLE QVariantList history() const;
/* None of these run during a turn; all return false when one does. */
Q_INVOKABLE bool newSession();
Q_INVOKABLE bool switchSession(const QString &id);
Q_INVOKABLE bool deleteSession(const QString &id);
Q_INVOKABLE bool renameSession(const QString &id, const QString &title);
/* The engine, for the parts that need it (tool registration). */
cst_agent_t *agent() const { return m_agent; }
const cst_agent_config_t *config() const { return &m_cfg; }
@@ -85,6 +103,8 @@ class AgentCore : public QObject {
void configChanged();
void approvalChanged();
void planModeChanged();
void sessionChanged(); /* another session is open now */
void sessionListChanged(); /* the store gained, lost or renamed one */
void statusChanged(const QString &text);
void assistantDelta(const QString &text);
void thinkDelta(const QString &text);
@@ -104,6 +124,8 @@ class AgentCore : public QObject {
friend class Turn;
void finishTurn(int rc, const QString &err);
void setRunning(bool on);
/* Re-read what a session switch changed (id, todo) and say so. */
void afterSessionChange();
/* Hook trampolines (C, run on the worker thread). */
static void hookStatus(const char *msg, void *ud);