Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

fix: handle errors gracefully in the post-generator streaming path

Gilad Resisife40b5877e81
diff --git a/apps/backend/src/api/routes/posts.controller.ts b/apps/backend/src/api/routes/posts.controller.ts
index 55e4b6d62..4095d651f 100644
--- a/apps/backend/src/api/routes/posts.controller.ts
+++ b/apps/backend/src/api/routes/posts.controller.ts
@@ -240,8 +240,21 @@ export class PostsController {
@Res({ passthrough: false }) res: Response
) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
- for await (const event of this._agentGraphService.start(org.id, body)) {
- res.write(JSON.stringify(event) + '\n');
+ try {
+ for await (const event of this._agentGraphService.start(org.id, body)) {
+ res.write(JSON.stringify(event) + '\n');
+ }
+ } catch (err) {
+ // The stream has already started, so we cannot surface a normal HTTP
+ // error here. Emit a final error event on the open stream instead, so the
+ // client can stop and show the message rather than hang on a truncated
+ // stream. HttpExceptions carry a curated, user-facing message (e.g. the
+ // AI safety rejection); anything else gets a generic message.
+ const message =
+ err instanceof HttpException
+ ? err.message
+ : 'Something went wrong while generating your posts, please try again.';
+ res.write(JSON.stringify({ name: 'error', error: true, message }) + '\n');
}
res.end();
diff --git a/apps/frontend/src/components/launches/generator/generator.tsx b/apps/frontend/src/components/launches/generator/generator.tsx
index 0bb0719cf..85ff61ae7 100644
--- a/apps/frontend/src/components/launches/generator/generator.tsx
+++ b/apps/frontend/src/components/launches/generator/generator.tsx
@@ -21,11 +21,13 @@ import dayjs from 'dayjs';
import { Select } from '@gitroom/react/form/select';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';
+import { useToaster } from '@gitroom/react/toaster/toaster';
const FirstStep: FC = (props) => {
const { integrations, reloadCalendarView } = useCalendar();
const modal = useModals();
const fetch = useFetch();
+ const toaster = useToaster();
const [loading, setLoading] = useState(false);
const [showStep, setShowStep] = useState('');
const t = useT();
@@ -59,8 +61,23 @@ const FirstStep: FC = (props) => {
for (const chunk of chunkStr
.split('\n')
.filter((f) => f && f.indexOf('{') > -1)) {
+ let data: any;
try {
- const data = JSON.parse(chunk);
+ data = JSON.parse(chunk);
+ } catch (e) {
+ /** ignore partial / unparseable chunks **/
+ continue;
+ }
+
+ // Server emits this when a node in the generation graph throws.
+ if (data?.error) {
+ throw new Error(
+ data.message ||
+ t('generation_failed', 'Failed to generate posts, please try again.')
+ );
+ }
+
+ {
switch (data.name) {
case 'agent':
setShowStep(t('agent_starting', 'Agent starting'));
@@ -108,8 +125,6 @@ const FirstStep: FC = (props) => {
break;
}
lastResponse = data;
- } catch (e) {
- /** don't do anything **/
}
}
}
@@ -121,66 +136,83 @@ const FirstStep: FC = (props) => {
}> = useCallback(
async (value) => {
setLoading(true);
- const response = await fetch('/posts/generator', {
- method: 'POST',
- body: JSON.stringify(value),
- });
- if (!response.body) {
- return;
- }
- const reader = response.body.getReader();
- const load = await generateStep(reader);
- const messages = load.content.map((p: any, index: number) => {
- if (index === 0) {
+ try {
+ const response = await fetch('/posts/generator', {
+ method: 'POST',
+ body: JSON.stringify(value),
+ });
+ if (!response.body) {
+ throw new Error(
+ t('generation_failed', 'Failed to generate posts, please try again.')
+ );
+ }
+ const reader = response.body.getReader();
+ const load = await generateStep(reader);
+ if (!load?.content) {
+ throw new Error(
+ t('generation_failed', 'Failed to generate posts, please try again.')
+ );
+ }
+ const messages = load.content.map((p: any, index: number) => {
+ if (index === 0) {
+ return {
+ content: load.hook + '\n' + p.content,
+ ...(p?.image?.path
+ ? {
+ image: [p.image],
+ }
+ : {}),
+ };
+ }
return {
- content: load.hook + '\n' + p.content,
+ content: p.content,
...(p?.image?.path
? {
image: [p.image],
}
: {}),
};
- }
- return {
- content: p.content,
- ...(p?.image?.path
- ? {
- image: [p.image],
- }
- : {}),
- };
- });
- setShowStep('');
- modal.openModal({
- id: 'add-edit-modal',
- closeOnClickOutside: false,
- removeLayout: true,
- closeOnEscape: false,
- withCloseButton: false,
- askClose: true,
- fullScreen: true,
- classNames: {
- modal: 'w-[100%] max-w-[1400px] text-textColor',
- },
- children: (
- <AddEditModal
- allIntegrations={integrations.map((p) => ({
- ...p,
- }))}
- integrations={integrations.slice(0).map((p) => ({
- ...p,
- }))}
- mutate={reloadCalendarView}
- date={dayjs.utc(load.date).local()}
- reopenModal={() => ({})}
- onlyValues={messages}
- />
- ),
- size: '80%',
- });
- setLoading(false);
+ });
+ setShowStep('');
+ modal.openModal({
+ id: 'add-edit-modal',
+ closeOnClickOutside: false,
+ removeLayout: true,
+ closeOnEscape: false,
+ withCloseButton: false,
+ askClose: true,
+ fullScreen: true,
+ classNames: {
+ modal: 'w-[100%] max-w-[1400px] text-textColor',
+ },
+ children: (
+ <AddEditModal
+ allIntegrations={integrations.map((p) => ({
+ ...p,
+ }))}
+ integrations={integrations.slice(0).map((p) => ({
+ ...p,
+ }))}
+ mutate={reloadCalendarView}
+ date={dayjs.utc(load.date).local()}
+ reopenModal={() => ({})}
+ onlyValues={messages}
+ />
+ ),
+ size: '80%',
+ });
+ } catch (e: any) {
+ toaster.show(
+ e?.message ||
+ t('generation_failed', 'Failed to generate posts, please try again.'),
+ 'warning'
+ );
+ } finally {
+ setShowStep('');
+ setLoading(false);
+ }
},
- [integrations, reloadCalendarView]
+ [integrations, reloadCalendarView, fetch, generateStep, modal, toaster, t]
);
return (
<form