ollie/kde/gui/chatblockmodel.cpp

1061 lines
38 KiB
C++

#include "chatblockmodel.h"
#include <QTextDocument>
#include <QRegularExpressionMatch>
#include <QApplication>
#include <QPalette>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
#include <QCryptographicHash>
#include <KSyntaxHighlighting/Repository>
#include <KSyntaxHighlighting/Definition>
#include <KSyntaxHighlighting/Theme>
#include <KSyntaxHighlighting/AbstractHighlighter>
#include <KSyntaxHighlighting/State>
#include <KSyntaxHighlighting/Format>
// --- Syntax highlighting ---
class HtmlHighlighter : public KSyntaxHighlighting::AbstractHighlighter
{
public:
QString html;
QString defaultColor; // Fallback color for unhighlighted text
using AbstractHighlighter::AbstractHighlighter;
KSyntaxHighlighting::State processLine(const QString &line,
const KSyntaxHighlighting::State &state)
{
m_line = line;
m_offset = 0;
return highlightLine(line, state);
}
void endLine() {
// Emit any remaining unhighlighted text at end of line
if (m_offset < m_line.length()) {
html += escapeHtml(m_line.mid(m_offset));
}
}
protected:
void applyFormat(int offset, int length,
const KSyntaxHighlighting::Format &format) override
{
// Emit any unhighlighted text before this span
if (offset > m_offset) {
const QString gap = m_line.mid(m_offset, offset - m_offset);
html += escapeHtml(gap);
}
m_offset = offset + length;
const QString text = escapeHtml(m_line.mid(offset, length));
if (format.hasTextColor(theme())) {
html += QStringLiteral("<span style=\"color:")
+ format.textColor(theme()).name()
+ QStringLiteral("\">") + text + QStringLiteral("</span>");
} else if (!defaultColor.isEmpty()) {
html += QStringLiteral("<span style=\"color:")
+ defaultColor
+ QStringLiteral("\">") + text + QStringLiteral("</span>");
} else {
html += text;
}
}
private:
QString escapeHtml(const QString &text) const {
return text.toHtmlEscaped()
.replace(QStringLiteral(" "), QStringLiteral("&nbsp;"))
.replace(QStringLiteral("\t"), QStringLiteral("&nbsp;&nbsp;&nbsp;&nbsp;"));
}
QString m_line;
int m_offset = 0;
};
// --- Static helpers ---
static ChatBlock::Type blockTypeFromString(const QString &typeStr)
{
if (typeStr == "user") return ChatBlock::User;
if (typeStr == "assistant") return ChatBlock::Assistant;
if (typeStr == "reasoning") return ChatBlock::Reasoning;
if (typeStr == "call") return ChatBlock::Call;
if (typeStr == "tool") return ChatBlock::Tool;
if (typeStr == "error") return ChatBlock::Error;
if (typeStr == "info") return ChatBlock::Info;
if (typeStr == "retry") return ChatBlock::Retry;
return ChatBlock::Default;
}
// --- Block Parsing ---
const QRegularExpression ChatBlockModel::s_headerRe(
R"(^\[\[\[([^\]]+)\]\]\]$)");
const QRegularExpression ChatBlockModel::s_endRe(
R"(^\[\[\[end\]\]\]$)");
// Matches opening fence: ```lang or just ```
const QRegularExpression ChatBlockModel::s_fenceOpenRe(
R"(^```([A-Za-z0-9_+.-]*).*$)");
// Matches closing fence: ``` on its own line
const QRegularExpression ChatBlockModel::s_fenceCloseRe(
R"(^```$)");
ChatBlockModel::ChatBlockModel(QObject *parent)
: QAbstractListModel(parent)
, m_repo(new KSyntaxHighlighting::Repository())
, m_netManager(new QNetworkAccessManager(this))
{
connect(m_netManager, &QNetworkAccessManager::finished,
this, &ChatBlockModel::onDiagramReply);
}
ChatBlockModel::~ChatBlockModel()
{
delete m_repo;
}
int ChatBlockModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) return 0;
return m_blocks.size();
}
QVariant ChatBlockModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= m_blocks.size())
return {};
const ChatBlock &b = m_blocks[index.row()];
switch (role) {
case BlockTypeRole:
switch (b.type) {
case ChatBlock::User: return QStringLiteral("user");
case ChatBlock::Assistant: return QStringLiteral("assistant");
case ChatBlock::Reasoning: return QStringLiteral("reasoning");
case ChatBlock::Call: return QStringLiteral("call");
case ChatBlock::Tool: return QStringLiteral("tool");
case ChatBlock::Error: return QStringLiteral("error");
case ChatBlock::Info: return QStringLiteral("info");
case ChatBlock::Retry: return QStringLiteral("retry");
case ChatBlock::Interrupt: return QStringLiteral("interrupt");
case ChatBlock::Default: return QStringLiteral("default");
}
return {};
case BlockNameRole:
return b.name;
case ContentRole:
return b.content;
case RenderedHtmlRole:
return b.renderedHtml;
case SegmentsRole:
return segmentsToVariant(b.segments);
case BlockIdRole:
return b.blockId;
}
return {};
}
QVariantList ChatBlockModel::segmentsToVariant(const QList<BlockSegment> &segments) const
{
QVariantList result;
for (const BlockSegment &seg : segments) {
QVariantMap m;
m[QStringLiteral("type")] = (seg.type == BlockSegment::Text)
? QStringLiteral("text") : QStringLiteral("diagram");
m[QStringLiteral("html")] = seg.html;
if (seg.type == BlockSegment::Diagram) {
m[QStringLiteral("lang")] = seg.diagramLang;
m[QStringLiteral("source")] = seg.diagramSource;
m[QStringLiteral("svg")] = seg.diagramSvg;
m[QStringLiteral("error")] = seg.diagramError;
m[QStringLiteral("loading")] = seg.diagramLoading;
}
result.append(m);
}
return result;
}
QHash<int, QByteArray> ChatBlockModel::roleNames() const
{
return {
{BlockTypeRole, "blockType"},
{BlockNameRole, "blockName"},
{ContentRole, "blockContent"},
{RenderedHtmlRole, "blockRenderedHtml"},
{SegmentsRole, "blockSegments"},
{BlockIdRole, "blockId"},
};
}
void ChatBlockModel::appendData(const QString &text)
{
m_lineBuffer += text;
int idx;
while ((idx = m_lineBuffer.indexOf('\n')) >= 0) {
QString line = m_lineBuffer.left(idx);
m_lineBuffer = m_lineBuffer.mid(idx + 1);
processLine(line);
}
// For streaming: update current block with partial line buffer content
// so the UI shows text as it arrives, not just after newlines.
if (!m_lineBuffer.isEmpty() && !m_blocks.isEmpty() && m_state == State::BlockEnd) {
int blockIndex = m_blocks.size() - 1;
ChatBlock &last = m_blocks[blockIndex];
// Save current segment state, render with partial line, then restore
QList<BlockSegment> savedSegments = last.segments;
QString savedHtml = last.renderedHtml;
renderLastSegmentPartial(blockIndex, m_lineBuffer);
// Emit the partial-updated view
QModelIndex idx = index(blockIndex);
emit dataChanged(idx, idx, {RenderedHtmlRole, SegmentsRole});
// Restore — partial line not committed yet
last.segments = savedSegments;
last.renderedHtml = savedHtml;
}
}
void ChatBlockModel::reset()
{
beginResetModel();
m_blocks.clear();
m_lineBuffer.clear();
m_inContext = false;
m_state = State::BlockStart;
m_inCodeFence = false;
m_fenceLanguage.clear();
m_fenceContent.clear();
m_pendingDiagrams.clear();
m_inFlightRequests.clear();
endResetModel();
emit countChanged();
}
void ChatBlockModel::trimFront(int keepCount)
{
if (m_blocks.size() <= keepCount)
return;
int removeCount = m_blocks.size() - keepCount;
beginRemoveRows(QModelIndex(), 0, removeCount - 1);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
m_blocks.remove(0, removeCount);
#else
m_blocks.erase(m_blocks.begin(), m_blocks.begin() + removeCount);
#endif
endRemoveRows();
emit countChanged();
}
int ChatBlockModel::indexForBlockId(const QString &blockId) const
{
for (int i = 0; i < m_blocks.size(); ++i) {
if (m_blocks[i].blockId == blockId)
return i;
}
return -1;
}
QString ChatBlockModel::getDefaultTextColor() const
{
const auto textColor = QApplication::palette().color(QPalette::Text);
return textColor.name();
}
QString ChatBlockModel::highlightCode(const QString &code, const QString &language) const
{
auto definition = m_repo->definitionForName(language);
if (!definition.isValid())
definition = m_repo->definitionForFileName(QStringLiteral("file.") + language);
const bool dark = QApplication::palette().color(QPalette::Window).lightnessF() < 0.5;
const auto theme = dark
? m_repo->defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)
: m_repo->defaultTheme(KSyntaxHighlighting::Repository::LightTheme);
const QString defaultColor = getDefaultTextColor();
// No valid definition — just escape and return
if (!definition.isValid()) {
QString result = QStringLiteral("<pre style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">");
result += code.toHtmlEscaped();
result += QStringLiteral("</pre>");
return result;
}
HtmlHighlighter highlighter;
highlighter.setDefinition(definition);
highlighter.setTheme(theme);
highlighter.defaultColor = defaultColor;
KSyntaxHighlighting::State state;
const QStringList lines = code.split('\n');
for (int i = 0; i < lines.size(); ++i) {
state = highlighter.processLine(lines[i], state);
highlighter.endLine();
if (i + 1 < lines.size())
highlighter.html += QStringLiteral("<br/>");
}
QString result = QStringLiteral("<pre style=\"white-space:pre-wrap;\">");
result += highlighter.html;
result += QStringLiteral("</pre>");
return result;
}
QString ChatBlockModel::highlightCodeWrapped(const QString &innerHtml) const
{
return QStringLiteral("<pre style=\"white-space:pre-wrap;\">") + innerHtml + QStringLiteral("</pre>");
}
QString ChatBlockModel::escapeForHtml(const QString &text) const
{
const QString defaultColor = getDefaultTextColor();
QString result = QStringLiteral("<div style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">");
result += text.toHtmlEscaped();
result += QStringLiteral("</div>");
return result;
}
bool ChatBlockModel::isTableLine(const QString &line)
{
const QString trimmed = line.trimmed();
return trimmed.startsWith('|') && trimmed.endsWith('|') && trimmed.count('|') >= 2;
}
QString ChatBlockModel::renderTable(const QStringList &tableLines) const
{
const QString defaultColor = getDefaultTextColor();
QString html = QStringLiteral("<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\" style=\"color:")
+ defaultColor + QStringLiteral(";\">");
bool pastSeparator = false;
for (const QString &line : tableLines) {
const QString trimmed = line.trimmed();
// Skip separator rows (|---|---|)
static QRegularExpression sepRe(QStringLiteral(R"(^\|[\s:|-]+\|$)"));
if (sepRe.match(trimmed).hasMatch()) {
pastSeparator = true;
continue;
}
// Strip leading/trailing |, split by |
QString inner = trimmed;
if (inner.startsWith('|')) inner = inner.mid(1);
if (inner.endsWith('|')) inner.chop(1);
const QStringList cells = inner.split('|');
const QString tag = pastSeparator ? QStringLiteral("td") : QStringLiteral("th");
html += QStringLiteral("<tr>");
for (const QString &cell : cells) {
html += QStringLiteral("<") + tag + QStringLiteral(">")
+ cell.trimmed().toHtmlEscaped()
+ QStringLiteral("</") + tag + QStringLiteral(">");
}
html += QStringLiteral("</tr>");
}
html += QStringLiteral("</table>");
return html;
}
QString ChatBlockModel::renderProse(const QStringList &lines) const
{
QString html;
QStringList textRun;
QStringList tableRun;
auto flushText = [&]() {
if (!textRun.isEmpty()) {
html += escapeForHtml(textRun.join('\n'));
textRun.clear();
}
};
auto flushTable = [&]() {
if (!tableRun.isEmpty()) {
html += renderTable(tableRun);
tableRun.clear();
}
};
for (const QString &line : lines) {
if (isTableLine(line)) {
flushText();
tableRun.append(line);
} else {
flushTable();
textRun.append(line);
}
}
flushText();
flushTable();
return html;
}
void ChatBlockModel::rebuildBlockHtml(int blockIndex)
{
if (blockIndex < 0 || blockIndex >= m_blocks.size())
return;
ChatBlock &block = m_blocks[blockIndex];
QString html;
QList<BlockSegment> segments;
// Parse the block content for code fences
const QStringList lines = block.content.split('\n');
bool inFence = false;
QString fenceLang;
QStringList fenceLines;
QStringList proseLines;
auto flushProse = [&]() {
if (!proseLines.isEmpty()) {
QString proseHtml = renderProse(proseLines);
html += proseHtml;
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = proseHtml;
segments.append(seg);
proseLines.clear();
}
};
auto flushFence = [&](bool complete) {
if (fenceLines.isEmpty()) {
fenceLang.clear();
return;
}
const QString code = fenceLines.join('\n');
if (isDiagramLanguage(fenceLang)) {
BlockSegment seg;
seg.type = BlockSegment::Diagram;
seg.diagramLang = fenceLang;
seg.diagramSource = code;
seg.html = highlightCode(code, fenceLang); // Source view HTML
if (!complete) {
// Streaming — show placeholder, don't request yet
html += diagramPlaceholder(fenceLang);
seg.diagramLoading = true;
} else {
// Complete fence — render through the local diagram server.
html += diagramPlaceholder(fenceLang);
seg.diagramLoading = true;
requestDiagram(fenceLang, code, blockIndex);
}
segments.append(seg);
} else {
QString codeHtml = highlightCode(code, fenceLang);
html += codeHtml;
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = codeHtml;
segments.append(seg);
}
fenceLines.clear();
fenceLang.clear();
};
for (const QString &line : lines) {
if (!inFence) {
// Check for fence open
auto match = s_fenceOpenRe.match(line);
if (match.hasMatch()) {
flushProse();
inFence = true;
fenceLang = match.captured(1);
continue;
}
proseLines.append(line);
} else {
// Inside fence — check for close
if (s_fenceCloseRe.match(line).hasMatch()) {
flushFence(true); // complete
inFence = false;
continue;
}
fenceLines.append(line);
}
}
// Handle unclosed fence (streaming) or remaining prose
if (inFence) {
// Still inside a fence — render what we have (incomplete)
flushFence(false);
} else {
flushProse();
}
block.renderedHtml = html;
block.segments = segments;
// Reset incremental state to match the full rebuild
block.renderState = BlockRenderState();
}
void ChatBlockModel::appendContent(const QString &line)
{
if (m_blocks.isEmpty())
return;
int blockIndex = m_blocks.size() - 1;
ChatBlock &last = m_blocks[blockIndex];
if (!last.content.isEmpty())
last.content += '\n';
last.content += line;
incrementalAppend(blockIndex, line);
QModelIndex idx = index(blockIndex);
emit dataChanged(idx, idx, {ContentRole, RenderedHtmlRole, SegmentsRole});
}
void ChatBlockModel::rebuildRenderedHtmlFromSegments(ChatBlock &block)
{
QString html;
for (const BlockSegment &seg : block.segments)
html += seg.html;
block.renderedHtml = html;
}
void ChatBlockModel::incrementalAppend(int blockIndex, const QString &line)
{
ChatBlock &block = m_blocks[blockIndex];
BlockRenderState &rs = block.renderState;
rs.committedLineCount++;
if (!rs.inFence) {
// Check for fence open
auto match = s_fenceOpenRe.match(line);
if (match.hasMatch()) {
// Flush any accumulated table into a finalized segment
if (rs.inTable && !rs.tableLines.isEmpty()) {
if (!block.segments.isEmpty())
block.segments.last().html = renderTable(rs.tableLines);
rs.tableLines.clear();
rs.inTable = false;
}
// Flush any accumulated prose into a finalized text segment
if (!rs.proseLines.isEmpty()) {
// The last segment should already be Text with these prose lines;
// it was being built up incrementally. Mark it done.
rs.proseLines.clear();
}
rs.inFence = true;
rs.fenceLang = match.captured(1);
rs.fenceLines.clear();
// Add a new Text segment for the code fence (will be rebuilt each line)
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = highlightCode(QString(), rs.fenceLang);
block.segments.append(seg);
block.renderedHtml += seg.html;
return;
}
if (isTableLine(line)) {
// Transitioning from prose to table — flush prose, start table segment
if (!rs.inTable) {
if (!rs.proseLines.isEmpty())
rs.proseLines.clear();
rs.inTable = true;
rs.tableLines.clear();
rs.tableLines.append(line);
// Start a new segment for the table
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = renderTable(rs.tableLines);
block.segments.append(seg);
} else {
// Continue accumulating table lines
rs.tableLines.append(line);
if (!block.segments.isEmpty())
block.segments.last().html = renderTable(rs.tableLines);
}
rebuildRenderedHtmlFromSegments(block);
return;
}
// Non-table prose line
if (rs.inTable) {
// Table just ended — finalize the table segment, start new prose
rs.tableLines.clear();
rs.inTable = false;
}
// Normal prose line — extend or create last text segment
rs.proseLines.append(line);
// Incremental: escape only the new line and append to existing segment
const QString defaultColor = getDefaultTextColor();
const QString escapedLine = line.toHtmlEscaped();
// Only extend the last segment if it is an in-progress prose segment
// (identified by its trailing </div>). A finalized code fence segment
// ends in </pre> and must not be overwritten.
bool canExtend = !block.segments.isEmpty()
&& block.segments.last().type == BlockSegment::Text
&& block.segments.last().html.endsWith(QStringLiteral("</div>"));
if (canExtend) {
QString &segHtml = block.segments.last().html;
segHtml.chop(6); // remove trailing </div>
segHtml += '\n' + escapedLine + QStringLiteral("</div>");
} else {
// Start a new prose segment
rs.proseLines.clear();
rs.proseLines.append(line);
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = QStringLiteral("<div style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">")
+ escapedLine + QStringLiteral("</div>");
block.segments.append(seg);
}
// Rebuild renderedHtml from segments (concatenation is cheap)
rebuildRenderedHtmlFromSegments(block);
} else {
// Inside a fence — check for close
if (s_fenceCloseRe.match(line).hasMatch()) {
// Close the fence — finalize the segment
rs.inFence = false;
const QString code = rs.fenceLines.join('\n');
if (isDiagramLanguage(rs.fenceLang)) {
// Replace last segment with a diagram segment
BlockSegment seg;
seg.type = BlockSegment::Diagram;
seg.diagramLang = rs.fenceLang;
seg.diagramSource = code;
seg.html = highlightCode(code, rs.fenceLang);
seg.diagramLoading = true;
requestDiagram(rs.fenceLang, code, blockIndex);
// Replace the in-progress fence segment
if (!block.segments.isEmpty())
block.segments.last() = seg;
else
block.segments.append(seg);
} else {
// Normal code: finalize highlighted segment
QString codeHtml = highlightCode(code, rs.fenceLang);
if (!block.segments.isEmpty())
block.segments.last().html = codeHtml;
}
rs.fenceLang.clear();
rs.fenceLines.clear();
rebuildRenderedHtmlFromSegments(block);
} else {
// Append line to fence — incrementally highlight only the new line
rs.fenceLines.append(line);
// Get highlighter definition + theme
auto definition = m_repo->definitionForName(rs.fenceLang);
if (!definition.isValid())
definition = m_repo->definitionForFileName(QStringLiteral("file.") + rs.fenceLang);
if (definition.isValid()) {
const bool dark = QApplication::palette().color(QPalette::Window).lightnessF() < 0.5;
const auto hlTheme = dark
? m_repo->defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)
: m_repo->defaultTheme(KSyntaxHighlighting::Repository::LightTheme);
HtmlHighlighter highlighter;
highlighter.setDefinition(definition);
highlighter.setTheme(hlTheme);
highlighter.defaultColor = getDefaultTextColor();
// Add line break before new line (if not the first)
if (!rs.hlHtml.isEmpty())
rs.hlHtml += QStringLiteral("<br/>");
// Process only the new line, continuing from saved state
rs.hlState = highlighter.processLine(line, rs.hlState);
highlighter.endLine();
rs.hlHtml += highlighter.html;
if (!block.segments.isEmpty())
block.segments.last().html = highlightCodeWrapped(rs.hlHtml);
} else {
// No syntax def — just escape
if (!rs.hlHtml.isEmpty())
rs.hlHtml += '\n';
rs.hlHtml += line.toHtmlEscaped();
const QString defaultColor = getDefaultTextColor();
if (!block.segments.isEmpty())
block.segments.last().html = QStringLiteral("<pre style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">")
+ rs.hlHtml + QStringLiteral("</pre>");
}
rebuildRenderedHtmlFromSegments(block);
}
}
}
void ChatBlockModel::renderLastSegmentPartial(int blockIndex, const QString &partialLine)
{
if (blockIndex < 0 || blockIndex >= m_blocks.size())
return;
ChatBlock &block = m_blocks[blockIndex];
BlockRenderState &rs = block.renderState;
if (rs.inFence) {
// Show partial line appended to current fence — use cached state
auto definition = m_repo->definitionForName(rs.fenceLang);
if (!definition.isValid())
definition = m_repo->definitionForFileName(QStringLiteral("file.") + rs.fenceLang);
if (definition.isValid()) {
const bool dark = QApplication::palette().color(QPalette::Window).lightnessF() < 0.5;
const auto hlTheme = dark
? m_repo->defaultTheme(KSyntaxHighlighting::Repository::DarkTheme)
: m_repo->defaultTheme(KSyntaxHighlighting::Repository::LightTheme);
HtmlHighlighter highlighter;
highlighter.setDefinition(definition);
highlighter.setTheme(hlTheme);
highlighter.defaultColor = getDefaultTextColor();
// Process partial line from saved state (don't save back)
QString partialHtml = rs.hlHtml;
if (!partialHtml.isEmpty())
partialHtml += QStringLiteral("<br/>");
highlighter.processLine(partialLine, rs.hlState);
highlighter.endLine();
partialHtml += highlighter.html;
if (!block.segments.isEmpty())
block.segments.last().html = highlightCodeWrapped(partialHtml);
} else {
// No definition — simple escape
QString inner = rs.hlHtml;
if (!inner.isEmpty())
inner += '\n';
inner += partialLine.toHtmlEscaped();
const QString defaultColor = getDefaultTextColor();
if (!block.segments.isEmpty())
block.segments.last().html = QStringLiteral("<pre style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">")
+ inner + QStringLiteral("</pre>");
}
} else {
// Show partial line appended to current prose/table
if (rs.inTable) {
// Currently building a table — show partial line as part of the table
if (isTableLine(partialLine)) {
QStringList preview = rs.tableLines;
preview.append(partialLine);
if (!block.segments.isEmpty())
block.segments.last().html = renderTable(preview);
} else {
// Partial line breaks the table — just show it as escaped text after
const QString defaultColor = getDefaultTextColor();
const QString escapedPartial = partialLine.toHtmlEscaped();
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = QStringLiteral("<div style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">")
+ escapedPartial + QStringLiteral("</div>");
block.segments.append(seg);
}
} else {
const QString defaultColor = getDefaultTextColor();
const QString escapedPartial = partialLine.toHtmlEscaped();
if (!block.segments.isEmpty() && block.segments.last().type == BlockSegment::Text) {
// Temporarily append to the segment (caller will restore)
QString &segHtml = block.segments.last().html;
if (segHtml.endsWith(QStringLiteral("</div>"))) {
segHtml.chop(6);
segHtml += '\n' + escapedPartial + QStringLiteral("</div>");
} else {
segHtml = escapeForHtml((rs.proseLines + QStringList{partialLine}).join('\n'));
}
} else {
BlockSegment seg;
seg.type = BlockSegment::Text;
seg.html = QStringLiteral("<div style=\"white-space:pre-wrap;color:") + defaultColor + QStringLiteral("\">")
+ escapedPartial + QStringLiteral("</div>");
block.segments.append(seg);
}
}
}
rebuildRenderedHtmlFromSegments(block);
}
void ChatBlockModel::processLine(const QString &line)
{
switch (m_state) {
case State::BlockStart: {
// [[[blockname]]] starts a new block
QRegularExpressionMatch match = s_headerRe.match(line);
if (match.hasMatch()) {
const QString blockName = match.captured(1);
beginInsertRows(QModelIndex(), m_blocks.size(), m_blocks.size());
ChatBlock newBlock;
newBlock.type = blockTypeFromString(blockName.section(':', 0, 0));
newBlock.name = blockName.section(':', 1);
// Generate stable block ID: sequential counter + type + name hash
// The counter ensures uniqueness even for identical type/name pairs
QString idSource = QString::number(m_blockIdCounter++) + blockName;
newBlock.blockId = QString::fromLatin1(
QCryptographicHash::hash(idSource.toUtf8(), QCryptographicHash::Md5).toHex().left(12));
m_blocks.append(newBlock);
endInsertRows();
emit countChanged();
m_state = State::BlockEnd;
}
// Lines outside blocks are ignored
return;
}
case State::BlockEnd:
// Hide prompt context blocks from the rendered chat, matching olliesrv.
if (line.trimmed() == QStringLiteral("<context>")) {
m_inContext = true;
return;
}
if (line.trimmed() == QStringLiteral("</context>")) {
m_inContext = false;
return;
}
if (m_inContext)
return;
// [[[end]]] closes the current block
if (s_endRe.match(line).hasMatch()) {
// Emit final update so QML picks up the completed segment state.
if (!m_blocks.isEmpty()) {
int blockIndex = m_blocks.size() - 1;
QModelIndex idx = index(blockIndex);
emit dataChanged(idx, idx, {ContentRole, RenderedHtmlRole, SegmentsRole});
}
m_state = State::BlockStart;
return;
}
appendContent(line);
return;
}
}
// --- Diagram rendering ---
bool ChatBlockModel::isDiagramLanguage(const QString &lang) const
{
const QString l = lang.toLower();
return l == QStringLiteral("plantuml") ||
l == QStringLiteral("mermaid") ||
l == QStringLiteral("puml");
}
QString ChatBlockModel::diagramPlaceholder(const QString &lang) const
{
const QString defaultColor = getDefaultTextColor();
return QStringLiteral("<div style=\"padding:8px;border:1px dashed ") + defaultColor +
QStringLiteral(";color:") + defaultColor +
QStringLiteral(";font-style:italic;\">Loading ") +
lang.toHtmlEscaped() + QStringLiteral(" diagram...</div>");
}
QString ChatBlockModel::diagramErrorHtml(const QString &error) const
{
return QStringLiteral("<div style=\"padding:8px;border:1px solid red;color:red;\">") +
QStringLiteral("Diagram error: ") + error.toHtmlEscaped() +
QStringLiteral("</div>");
}
QString ChatBlockModel::diagramSvgHtml(const QByteArray &svg) const
{
// Embed SVG inline as data URI
const QString base64 = QString::fromLatin1(svg.toBase64());
return QStringLiteral("<img src=\"data:image/svg+xml;base64,") + base64 +
QStringLiteral("\" style=\"max-width:100%;\" />");
}
QString ChatBlockModel::diagramPngHtml(const QByteArray &png) const
{
// Embed PNG inline as data URI
const QString base64 = QString::fromLatin1(png.toBase64());
return QStringLiteral("<img src=\"data:image/png;base64,") + base64 +
QStringLiteral("\" style=\"max-width:100%;\" />");
}
QString ChatBlockModel::diagramJpegHtml(const QByteArray &jpeg) const
{
// Embed JPEG inline as data URI
const QString base64 = QString::fromLatin1(jpeg.toBase64());
return QStringLiteral("<img src=\"data:image/jpeg;base64,") + base64 +
QStringLiteral("\" style=\"max-width:100%;\" />");
}
void ChatBlockModel::requestDiagram(const QString &lang, const QString &code, int blockIndex)
{
const QString requestKey = lang + QStringLiteral(":") +
QString::fromLatin1(QCryptographicHash::hash(
code.toUtf8(), QCryptographicHash::Md5).toHex());
// Track duplicate requests only while this local render is in flight.
if (!m_pendingDiagrams.contains(requestKey))
m_pendingDiagrams[requestKey] = QList<int>();
if (!m_pendingDiagrams[requestKey].contains(blockIndex))
m_pendingDiagrams[requestKey].append(blockIndex);
if (m_inFlightRequests.contains(requestKey))
return;
m_inFlightRequests.insert(requestKey);
QNetworkRequest request;
request.setAttribute(QNetworkRequest::User, requestKey);
request.setTransferTimeout(10000);
const QString langLower = lang.toLower();
if (langLower == QStringLiteral("plantuml") || langLower == QStringLiteral("puml")) {
// PlantUML server accepts POST with raw source
request.setUrl(QUrl(QStringLiteral("http://localhost:8080/svg")));
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("text/plain"));
m_netManager->post(request, code.toUtf8());
} else if (langLower == QStringLiteral("mermaid")) {
// Mermaid-ink expects base64 in URL path, /img/ for PNG output
// (SVG uses foreignObject which Qt's SVG renderer doesn't support)
const QByteArray encoded = code.toUtf8().toBase64();
request.setUrl(QUrl(QStringLiteral("http://localhost:8081/img/") + QString::fromLatin1(encoded)));
m_netManager->get(request);
} else {
m_inFlightRequests.remove(requestKey);
return;
}
}
void ChatBlockModel::onDiagramReply(QNetworkReply *reply)
{
reply->deleteLater();
const QString cacheKey = reply->request().attribute(QNetworkRequest::User).toString();
m_inFlightRequests.remove(cacheKey);
QByteArray imageData;
bool success = false;
QString errorMsg;
if (reply->error() == QNetworkReply::NoError) {
imageData = reply->readAll();
// Check for JPEG/PNG (mermaid) or SVG (plantuml)
if (imageData.startsWith("\xff\xd8\xff")) {
// JPEG image
success = true;
imageData.prepend("JPEG:");
} else if (imageData.startsWith("\x89PNG")) {
// PNG image
success = true;
imageData.prepend("PNG:");
} else if (imageData.contains("<svg") || imageData.startsWith("<?xml")) {
// SVG image
success = true;
imageData.prepend("SVG:");
} else {
errorMsg = QStringLiteral("Invalid response (not SVG, PNG, or JPEG)");
}
} else {
errorMsg = reply->errorString();
}
if (success) {
// Keep the result only on the waiting segments; do not cache diagrams.
} else {
// The error is applied directly to waiting segments below.
}
// Apply the response directly to waiting segments. Nothing is retained after
// this request completes; a later occurrence renders through the local server.
const QList<int> blocks = m_pendingDiagrams.take(cacheKey);
for (int blockIndex : blocks) {
if (blockIndex < 0 || blockIndex >= m_blocks.size())
continue;
ChatBlock &block = m_blocks[blockIndex];
BlockSegment *matchingSegment = nullptr;
for (BlockSegment &segment : block.segments) {
if (segment.type != BlockSegment::Diagram || !segment.diagramLoading)
continue;
const QString segmentKey = segment.diagramLang + QStringLiteral(":") +
QString::fromLatin1(QCryptographicHash::hash(
segment.diagramSource.toUtf8(), QCryptographicHash::Md5).toHex());
if (segmentKey == cacheKey) {
matchingSegment = &segment;
break;
}
}
// A block can be rebuilt while a request is in flight. In that case
// the segment still represents this request, but its source may have
// been normalized by the parser. Use the sole pending diagram rather
// than leaving the UI loading forever.
if (!matchingSegment) {
for (BlockSegment &segment : block.segments) {
if (segment.type == BlockSegment::Diagram && segment.diagramLoading) {
if (matchingSegment) {
matchingSegment = nullptr;
break;
}
matchingSegment = &segment;
}
}
}
if (!matchingSegment)
continue;
BlockSegment &segment = *matchingSegment;
segment.diagramLoading = false;
if (!success) {
segment.diagramError = errorMsg;
segment.html = diagramErrorHtml(errorMsg);
} else if (imageData.startsWith("JPEG:")) {
const QByteArray data = imageData.mid(5);
segment.diagramSvg = QStringLiteral("data:image/jpeg;base64,") +
QString::fromLatin1(data.toBase64());
segment.html = diagramJpegHtml(data);
} else if (imageData.startsWith("PNG:")) {
const QByteArray data = imageData.mid(4);
segment.diagramSvg = QStringLiteral("data:image/png;base64,") +
QString::fromLatin1(data.toBase64());
segment.html = diagramPngHtml(data);
} else {
const QByteArray data = imageData.startsWith("SVG:") ? imageData.mid(4) : imageData;
segment.diagramSvg = QStringLiteral("data:image/svg+xml;base64,") +
QString::fromLatin1(data.toBase64());
segment.html = diagramSvgHtml(data);
}
rebuildRenderedHtmlFromSegments(block);
QModelIndex idx = index(blockIndex);
emit dataChanged(idx, idx, {RenderedHtmlRole, SegmentsRole});
}
}