Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
381e5d3107 | ||
|
|
c14df6c049 | ||
|
|
ece7cdd36f |
@@ -99,7 +99,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.21.0",
|
||||
"version": "0.21.1",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import TaskListItem from "./task-list-item";
|
||||
|
||||
const base_task: TaskWithNames = {
|
||||
id: 42,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
bot_id: 3,
|
||||
bot_name: "Software Engineer",
|
||||
status: "todo",
|
||||
};
|
||||
|
||||
describe("TaskListItem", () => {
|
||||
test("appends the task's id to its title, so the list can be matched to a [task:ID]", () => {
|
||||
const html = renderToString(<TaskListItem task={{ ...base_task, title: "Fix the header" }} />);
|
||||
|
||||
expect(html).toContain("Fix the header");
|
||||
expect(html).toContain("#42");
|
||||
});
|
||||
|
||||
test("an untitled task is named by its id alone, never twice", () => {
|
||||
const html = renderToString(<TaskListItem task={{ ...base_task, title: "" }} />);
|
||||
|
||||
expect(html).toContain("Task 42");
|
||||
expect(html).not.toContain("#42");
|
||||
});
|
||||
|
||||
test("a dropped workspace task shows its id too", () => {
|
||||
const html = renderToString(
|
||||
<TaskListItem task={{ ...base_task, title: "Workspace wide", bot_id: "", workspace_id: 7 }} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Workspace wide");
|
||||
expect(html).toContain("#42");
|
||||
});
|
||||
});
|
||||
@@ -71,10 +71,19 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
|
||||
onClick={onOpen}
|
||||
className={twMerge(
|
||||
"grow min-w-0 justify-start px-0! h-auto! py-0! text-sm! font-bold! leading-5! truncate text-left hover:bg-transparent! hover:underline",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:gap-1.5",
|
||||
done ? "text-ink-secondary! line-through" : "text-ink!",
|
||||
)}
|
||||
>
|
||||
<Span className="truncate">{task.title || `Task ${task.id}`}</Span>
|
||||
{task.title ? (
|
||||
<Span
|
||||
title={`Task ${task.id}`}
|
||||
className="shrink-0 text-[11px] leading-4 font-normal text-ink-secondary tabular-nums"
|
||||
>
|
||||
{`#${task.id}`}
|
||||
</Span>
|
||||
) : null}
|
||||
</Button>
|
||||
<TaskStatusChip status={task.status} />
|
||||
{can_manage && onDelete ? (
|
||||
|
||||
@@ -9,6 +9,7 @@ import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
import askOutcomeMessage from "./ask-outcome-message";
|
||||
import stripQuestionRefs from "@/src/utils/strip-question-refs";
|
||||
|
||||
type Params = {
|
||||
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
|
||||
@@ -93,7 +94,15 @@ async function tellRequester({
|
||||
bot_id: requester.id,
|
||||
session_id: session.id,
|
||||
workspace_id: Number(ask.workspace_id) || null,
|
||||
text: askOutcomeMessage({ ask, status, outcome }),
|
||||
/**
|
||||
* A question the answer names stays in the conversation it was
|
||||
* asked in: its card here would answer into this one.
|
||||
*/
|
||||
text: askOutcomeMessage({
|
||||
ask,
|
||||
status,
|
||||
outcome: outcome ? stripQuestionRefs({ text: outcome }).text : outcome,
|
||||
}),
|
||||
from_ask_id: Number(ask.id),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
|
||||
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
|
||||
import grabBotQuestion from "./grab-bot-question";
|
||||
|
||||
type Params = {
|
||||
view: BotQuestionView;
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tells the bot, in the conversation its questions were asked in, what the
|
||||
* user answered (or that they skipped them): the user's chat message there,
|
||||
* which wakes it. The route posts this, not the card's page: the same
|
||||
* conversation can be on screen in several places, and an answer belongs
|
||||
* where the question was asked, never to whichever bot's page was open.
|
||||
* Best effort: a failure is logged and never undoes the answer.
|
||||
*/
|
||||
export default async function postBotQuestionAnswers({ view, user_id }: Params) {
|
||||
try {
|
||||
const row = await grabBotQuestion({ question_id: view.id, user_id });
|
||||
|
||||
if (!row.bot_id) return;
|
||||
|
||||
const session = await pickSession({ row, user_id });
|
||||
|
||||
const message = await insertUserMessage({
|
||||
bot_id: Number(row.bot_id),
|
||||
session_id: Number(session.id),
|
||||
workspace_id: session.workspace_id || null,
|
||||
text: botQuestionAnswersText({ view }),
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id: row.bot_id, message });
|
||||
|
||||
await enqueueBotReply({
|
||||
user_id,
|
||||
bot_id: row.bot_id,
|
||||
session_id: Number(session.id),
|
||||
message_id: Number(message.id),
|
||||
});
|
||||
|
||||
wakeBotsQueue();
|
||||
} catch (error: unknown) {
|
||||
await logError({
|
||||
title: `A bot's question answers didn't reach it`,
|
||||
error,
|
||||
metadata: { question_id: view.id },
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The session the questions were asked in while it's still where the bot
|
||||
* talks; otherwise its conversation's active one, so the answer isn't left
|
||||
* in a closed thread.
|
||||
*/
|
||||
async function pickSession({
|
||||
row,
|
||||
user_id,
|
||||
}: {
|
||||
row: Pick<BUN_SQLITE_COBBLE_BOT_QUESTIONS, "bot_id" | "session_id" | "workspace_id">;
|
||||
user_id: number | string;
|
||||
}): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
|
||||
const origin = row.session_id
|
||||
? await grabUserBotSession({ session_id: row.session_id, user_id })
|
||||
: null;
|
||||
|
||||
/**
|
||||
* A hidden session (a crew request's, a hook's) is only read there.
|
||||
*/
|
||||
if (origin?.id && origin.status == "active" && !origin.ask_id && !origin.hook_id) {
|
||||
return origin;
|
||||
}
|
||||
|
||||
return await ensureBotSession({
|
||||
user_id,
|
||||
bot_id: row.bot_id!,
|
||||
workspace_id: row.workspace_id || null,
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
} from "@/db/types/db";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import stripQuestionRefs from "@/src/utils/strip-question-refs";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -66,13 +67,24 @@ export default async function relayJobToRequester({ job, text, failed, task_ids
|
||||
const name = worker?.name || "A crew member";
|
||||
const title = job.title || "the job";
|
||||
|
||||
/**
|
||||
* The worker's questions stay in its own conversation: a card here
|
||||
* would be answered into this one, and the worker would never hear.
|
||||
*/
|
||||
const report = stripQuestionRefs({ text });
|
||||
const where = report.removed
|
||||
? `\n\n_They asked you something in their own conversation: [bot:${job.bot_id}]._`
|
||||
: "";
|
||||
|
||||
const message = await insertBotMessage({
|
||||
bot_id: requester.id,
|
||||
session_id: Number(session.id),
|
||||
workspace_id,
|
||||
text: failed
|
||||
? `${name} couldn't finish **${title}**. ${text}`.trim()
|
||||
: `${name} finished **${title}**. Their report:\n\n${text}`,
|
||||
text:
|
||||
(failed
|
||||
? `${name} couldn't finish **${title}**. ${report.text}`
|
||||
: `${name} finished **${title}**. Their report:\n\n${report.text}`
|
||||
).trim() + where,
|
||||
needs_you: failed,
|
||||
task_ids,
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import parseInstallPackages from "@/src/utils/parse-install-packages";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
|
||||
import stripQuestionRefs from "@/src/utils/strip-question-refs";
|
||||
|
||||
type Params = {
|
||||
job: Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id">;
|
||||
@@ -63,7 +64,11 @@ export default async function settleInstallRequest({ job, text, failed }: Params
|
||||
request_id: request.id,
|
||||
status: (request.status || "failed") as InstallRequestStatus,
|
||||
asked: installRequestAsked({ packages: parseInstallPackages({ text: request.packages }) }),
|
||||
answer: request.answer,
|
||||
/**
|
||||
* A question the coordinator asked stays in its own
|
||||
* conversation: a card here would answer into this one.
|
||||
*/
|
||||
answer: request.answer ? stripQuestionRefs({ text: request.answer }).text : request.answer,
|
||||
}),
|
||||
from_install_request_id: request.id,
|
||||
});
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useContext, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
|
||||
import checkBotQuestionAnswers from "@/src/utils/check-bot-question-answers";
|
||||
import decideBotQuestion from "../(functions)/decide-bot-question";
|
||||
import sendBotMessage from "../(functions)/send-bot-message";
|
||||
import botQuestionDraftAnswer, {
|
||||
type BotQuestionDraft,
|
||||
} from "../(utils)/bot-question-draft-answer";
|
||||
@@ -24,10 +21,10 @@ type Props = {
|
||||
* The card a user answers a bot's questions in: each question with its
|
||||
* options (radios for one pick, checkboxes for several, "Other" to type
|
||||
* their own). Sending or skipping tells the bot in chat, as the user's
|
||||
* message; once decided it shows what they answered.
|
||||
* message, in the conversation it asked in (the route posts it, since that
|
||||
* may not be the one on screen). Once decided it shows what they answered.
|
||||
*/
|
||||
export default function BotQuestionCard({ view, onDecided, onDone }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const [drafts, setDrafts] = useState<BotQuestionDraft[]>(() =>
|
||||
view.questions.map(() => ({ choices: [], other_on: false, other: "" })),
|
||||
);
|
||||
@@ -84,13 +81,6 @@ export default function BotQuestionCard({ view, onDecided, onDone }: Props) {
|
||||
|
||||
onDecided(res.singleRes);
|
||||
|
||||
await sendBotMessage({
|
||||
bot_id: Number(pageProps?.bot?.id) || 0,
|
||||
workspace_id: pageProps?.workspace?.id || null,
|
||||
text: botQuestionAnswersText({ view: res.singleRes }),
|
||||
media_ids: [],
|
||||
}).catch(() => null);
|
||||
|
||||
setBusy(undefined);
|
||||
onDone();
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import answerBotQuestion from "@/src/functions/backend/db/bot-questions/answer-bot-question";
|
||||
import grabBotQuestionView from "@/src/functions/backend/db/bot-questions/grab-bot-question-view";
|
||||
import postBotQuestionAnswers from "@/src/functions/backend/db/bot-questions/post-bot-question-answers";
|
||||
import { AnswerBotQuestionSchema } from "@/src/schemas/bot-question-schema";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
@@ -33,7 +34,15 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<BotQuestionView>>
|
||||
|
||||
await answerBotQuestion({ question_id, user_id: user.id, answers });
|
||||
|
||||
return { success: true, singleRes: await grabBotQuestionView({ question_id, user_id: user.id }) };
|
||||
const view = await grabBotQuestionView({ question_id, user_id: user.id });
|
||||
|
||||
/**
|
||||
* The answers go to the bot in the conversation it asked in, which
|
||||
* may not be the one the card was read from.
|
||||
*/
|
||||
await postBotQuestionAnswers({ view, user_id: user.id });
|
||||
|
||||
return { success: true, singleRes: view };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabBotQuestionView from "@/src/functions/backend/db/bot-questions/grab-bot-question-view";
|
||||
import postBotQuestionAnswers from "@/src/functions/backend/db/bot-questions/post-bot-question-answers";
|
||||
import skipBotQuestion from "@/src/functions/backend/db/bot-questions/skip-bot-question";
|
||||
import { BotQuestionIdSchema } from "@/src/schemas/bot-question-schema";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
@@ -32,7 +33,15 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<BotQuestionView>>
|
||||
|
||||
await skipBotQuestion({ question_id, user_id: user.id });
|
||||
|
||||
return { success: true, singleRes: await grabBotQuestionView({ question_id, user_id: user.id }) };
|
||||
const view = await grabBotQuestionView({ question_id, user_id: user.id });
|
||||
|
||||
/**
|
||||
* The refusal goes to the bot in the conversation it asked in, which
|
||||
* may not be the one the card was read from.
|
||||
*/
|
||||
await postBotQuestionAnswers({ view, user_id: user.id });
|
||||
|
||||
return { success: true, singleRes: view };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import stripQuestionRefs from "./strip-question-refs";
|
||||
|
||||
describe("stripQuestionRefs", () => {
|
||||
test("takes a question that ends a report out of it", () => {
|
||||
const { text, removed } = stripQuestionRefs({
|
||||
text: "I wrote the schema and seeded it.\n\nBefore I commit:\n\n[question:9]",
|
||||
});
|
||||
|
||||
expect(removed).toBe(true);
|
||||
expect(text).toBe("I wrote the schema and seeded it.\n\nBefore I commit:");
|
||||
});
|
||||
|
||||
test("takes every one of them out, in the middle of a line too", () => {
|
||||
const { text, removed } = stripQuestionRefs({
|
||||
text: "Asked [question:3] and [question:4] above, then waited.",
|
||||
});
|
||||
|
||||
expect(removed).toBe(true);
|
||||
expect(text).toBe("Asked and above, then waited.");
|
||||
});
|
||||
|
||||
test("leaves text with no question as it was", () => {
|
||||
const report = "Done.\n\n- Built it\n- Tested it\n";
|
||||
|
||||
expect(stripQuestionRefs({ text: report })).toEqual({ text: report, removed: false });
|
||||
});
|
||||
|
||||
test("leaves something that only looks like a ref alone", () => {
|
||||
expect(stripQuestionRefs({ text: "See [question:abc]." }).removed).toBe(false);
|
||||
});
|
||||
|
||||
test("takes its code span with it, since one quoted alone still links", () => {
|
||||
expect(stripQuestionRefs({ text: "Waiting on `[question:9]` here." }).text).toBe(
|
||||
"Waiting on here.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a report that was nothing but the question is empty", () => {
|
||||
expect(stripQuestionRefs({ text: "[question:9]\n" }).text).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
type Params = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
type Stripped = {
|
||||
text: string;
|
||||
/**
|
||||
* Whether anything was taken out, so the caller can say where the
|
||||
* question is waiting instead.
|
||||
*/
|
||||
removed: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A bot's question card, as its message names it (`[question:12]`).
|
||||
*/
|
||||
const QuestionRef = /\[question:\d+\]/;
|
||||
|
||||
/**
|
||||
* A ref between words leaves one space behind, never two: `[ \t]*` around it
|
||||
* stays on the same line, so paragraph breaks survive.
|
||||
*/
|
||||
const QuestionRefs = /[ \t]*\[question:\d+\][ \t]*/g;
|
||||
|
||||
/**
|
||||
* One quoted alone in its own code span (which still links), with the span.
|
||||
*/
|
||||
const QuestionRefCodeSpan = /`\s*\[question:\d+\]\s*`[ \t]?/g;
|
||||
|
||||
/**
|
||||
* A bot's own text with its `[question:ID]` refs taken out, for text copied
|
||||
* into another bot's conversation (`relayJobToRequester`, a crew request's
|
||||
* outcome, an install request's answer). A question belongs to the
|
||||
* conversation it was asked in: a copy elsewhere would show a second card
|
||||
* whose answer never reaches the bot that asked.
|
||||
*/
|
||||
export default function stripQuestionRefs({ text }: Params): Stripped {
|
||||
if (!QuestionRef.test(text)) return { text, removed: false };
|
||||
|
||||
return {
|
||||
text: text
|
||||
.replace(QuestionRefCodeSpan, "")
|
||||
.replace(QuestionRefs, " ")
|
||||
.replace(/[ \t]+$/gm, "")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim(),
|
||||
removed: true,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user