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
4 changes: 4 additions & 0 deletions docs/architecture/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ The KDS WebSocket is served at path `/kds` on **both** `:3001` and `:3002`. Both
same handler, `setupKdsWebSocket` in [`main/services/kds.ts`](../../main/services/kds.ts), so a
KDS client behaves identically whichever port it connects to.

The standalone KDS and Server App pages each link their own web app manifest
(`frontend/public/kds-manifest.json` and `frontend/public/server-manifest.json`), so an installed
app opens `/kds-standalone` or `/server-standalone` and not the POS dashboard.

```mermaid
flowchart TB
subgraph main["Electron main process"]
Expand Down
6 changes: 4 additions & 2 deletions docs/architecture/printing.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ the callout banner.
| --- | --- |
| Network | Raw socket (`printViaNetwork()` in `main/printers/thermal.ts`). Payloads over 4096 bytes (`NETWORK_PRINT_CHUNK_SIZE`) are sent in 4096-byte chunks with a 10 ms delay between chunks (`NETWORK_PRINT_CHUNK_DELAY_MS`), so a large receipt does not overrun the printer's buffer; smaller payloads are written in a single pass. After writing the payload, `printViaNetwork()` sends `DLE_EOT[1]` (`0x10 0x04 0x01`) and waits for a reply, peer close, or `NETWORK_PRINT_DRAIN_TIMEOUT_MS` (600 ms) before closing the socket so slower printer microcontrollers finish draining trailing commands without stalling silent printers. `validateNetworkPrinterTarget()` (enforced on `/api/printers` configuration, `/:id/status` probes, LAN discovery in `main/printers/lan-discovery.ts`, and `printViaNetwork()` dispatch) rejects cloud metadata endpoints, unspecified/broadcast addresses, and FloCafe's own local listening ports across canonical and non-canonical (shorthand, octal, hexadecimal, and integer) IPv4 forms while preserving hostnames, custom ports, LAN/Tailscale/IPv6 addresses, and link-local printers. |
| CUPS | `lp -d <printer> -o raw <tmpfile>`, using an exclusive (`wx`, `0600`) temporary file with a per-job UUID suffix that is unlinked only if created. |
| Windows | `OpenPrinterW` with `pDataType` set to `RAW`, reading an exclusive (`wx`, `0600`) temporary file with a per-job UUID suffix that is unlinked only if created. Before `StartDocPrinter`, the helper refuses a queue that is set to Use Printer Offline, offline, or not available. For those three refusals only, when the queue's port is a Standard TCP/IP port in RAW mode, `main/printers/windows-queue-bypass.ts` sends the same bytes once to that port with `printViaNetwork()`. No job exists in the spool at that point, so the bypass cannot print a ticket twice. When the port has SNMP status enabled, the failure detail says so and the POS shows how to turn it off. |
| Windows | `OpenPrinterW` with `pDataType` set to `RAW`, reading an exclusive (`wx`, `0600`) temporary file with a per-job UUID suffix that is unlinked only if created. Before `StartDocPrinter`, the helper refuses a queue that reports out of paper, paper jam, cover open, Use Printer Offline, offline, not available, or needs attention. The generic error status flag alone does not block the job; `StartDocPrinter`, `StartPagePrinter`, and `WritePrinter` failures still fail it. For the Use Printer Offline, offline, and not-available refusals only, when the queue's port is a Standard TCP/IP port in RAW mode, `main/printers/windows-queue-bypass.ts` sends the same bytes once to that port with `printViaNetwork()`. No job exists in the spool at that point, so the bypass cannot print a ticket twice. When the port has SNMP status enabled, the failure detail says so and the POS shows how to turn it off. |
| macOS Mac App Store | IPP over the local CUPS UNIX domain socket `/private/var/run/cupsd` (with loopback HTTP fallback on `127.0.0.1:631`) using `main/printers/ipp-client.ts` and `document-format` `application/vnd.cups-raw`, because the macOS App Sandbox blocks shelling out to `lp` and blocks outbound TCP to `localhost:631` while permitting `/private/var/run/cupsd` under `com.apple.security.print`. |
| WebUSB | The browser WebUSB API through the frontend bridge. A browser terminal needs a secure origin, so it opens FloCafe over the [Secure Network](overview.md#secure-network-https-for-lan-devices) HTTPS address; the desktop app uses `localhost`, which is already secure. Permissions are per origin. |

Expand All @@ -233,7 +233,9 @@ socket and decodes the answer into online, cover open, paper out, paper near end
The probe never throws, and it returns when the first query gets no answer, so a printer that does
not implement `DLE EOT` costs one timeout. `statusToFailureCause()` maps the result to one cause:
`paper_out`, `cover_open`, `printer_error`, `offline`, or `unreachable`. USB queues report
`queue_offline` or `queue_missing` from OS detection. After a test print to a network printer, the
`queue_offline` or `queue_missing` from OS detection. On Windows a queue is offline only when
`Win32_Printer.WorkOffline` is true or `PrinterStatus` is 6 (Stopped Printing) or 7 (Offline);
Other and Unknown count as not offline. After a test print to a network printer, the
route probes that printer and treats `paper_out`, `cover_open`, `printer_error`, and `offline` as
failures (preserving `failure_class` from dispatch when more specific, such as `timeout`), because a
raw socket can accept bytes that an offline or faulted printer drops. The frontend turns the cause,
Expand Down
25 changes: 25 additions & 0 deletions frontend/public/kds-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"id": "/kds-standalone",
"name": "Flo KDS",
"short_name": "Flo KDS",
"description": "Kitchen Display System",
"start_url": "/kds-standalone",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#3248FF",
"orientation": "any",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}
25 changes: 25 additions & 0 deletions frontend/public/server-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"id": "/server-standalone",
"name": "Flo Server App",
"short_name": "Flo Server",
"description": "Tableside ordering for FloCafe",
"start_url": "/server-standalone",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#3248FF",
"orientation": "any",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}
8 changes: 3 additions & 5 deletions frontend/src/app/kds-standalone/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import { KdsHtmlLang } from '@/components/kds/KdsHtmlLang';
export const metadata: Metadata = {
title: 'Flo KDS - Kitchen Display',
description: 'Kitchen Display System',
// The root manifest starts at /dashboard, which the KDS server cannot back.
manifest: '/kds-manifest.json',
};

export default function KdsStandaloneLayout({
children,
}: {
children: React.ReactNode;
}) {
export default function KdsStandaloneLayout({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-screen h-full flex flex-col p-4 bg-muted">
<KdsHtmlLang />
Expand Down
8 changes: 3 additions & 5 deletions frontend/src/app/server-standalone/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@ const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'Flo Server App',
description: 'Tableside ordering for FloCafe',
// The root manifest starts at /dashboard, which the Server App cannot back.
manifest: '/server-manifest.json',
};

export default function ServerStandaloneLayout({
children,
}: {
children: React.ReactNode;
}) {
export default function ServerStandaloneLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning className="h-full">
<body className={`${inter.className} h-full bg-slate-50 dark:bg-background`}>
Expand Down
26 changes: 15 additions & 11 deletions main/printers/thermal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,11 +740,11 @@ function windowsPowerShellCommandArgs(script: string): string[] {
}

// Enumerate printers via Get-CimInstance (Win32_Printer) using -EncodedCommand.
const DETECT_WINDOWS_PRINTERS_SCRIPT = `
export const DETECT_WINDOWS_PRINTERS_SCRIPT = `
$ErrorActionPreference = 'Stop'
try {
Get-CimInstance -ClassName Win32_Printer -Property Name,Default,PrinterStatus,DriverName |
Select-Object Name,Default,PrinterStatus,DriverName |
Get-CimInstance -ClassName Win32_Printer -Property Name,Default,PrinterStatus,WorkOffline,DriverName |
Select-Object Name,Default,PrinterStatus,WorkOffline,DriverName |
ConvertTo-Json -Compress
} catch {
[Console]::Error.WriteLine($_.Exception.Message)
Expand All @@ -754,10 +754,14 @@ try {
`;

// Win32_Printer.PrinterStatus: 1=Other, 2=Unknown, 3=Idle, 4=Printing, 5=Warming Up, 6=Stopped Printing, 7=Offline.
function mapWindowsPrinterStatus(printerStatus: unknown): 'idle' | 'printing' | 'offline' {
if (printerStatus === 3 || printerStatus === 5) return 'idle';
if (printerStatus === 4) return 'printing';
return 'offline';
// USB queues often report Other or Unknown while ready, so only explicit offline signals count.
export function mapWindowsPrinterStatus(entry: {
PrinterStatus?: unknown;
WorkOffline?: unknown;
}): 'idle' | 'printing' | 'offline' {
const { PrinterStatus: status, WorkOffline: workOffline } = entry;
if (workOffline === true || status === 6 || status === 7) return 'offline';
return status === 4 ? 'printing' : 'idle';
}

async function detectWindowsPrinters(signal?: AbortSignal): Promise<PrinterInfo[]> {
Expand Down Expand Up @@ -796,7 +800,7 @@ async function detectWindowsPrinters(signal?: AbortSignal): Promise<PrinterInfo[
connectionType: 'usb',
deviceUri: name,
driver,
status: mapWindowsPrinterStatus(entry.PrinterStatus),
status: mapWindowsPrinterStatus(entry),
isDefault: entry.Default === true,
paperWidth: guessPaperWidth(name, makeModel.model),
}),
Expand Down Expand Up @@ -5697,12 +5701,12 @@ public static class FloRawPrinter {
if ((status & 0x00000080) != 0) return "printer is offline";
if ((status & 0x00001000) != 0) return "printer is not available";
if ((status & 0x00100000) != 0) return "printer needs attention";
if ((status & 0x00000002) != 0) return "printer reported an error";
// The generic error flag (0x2) is not checked: Windows still prints with it set.
return null;
}

// OpenPrinter succeeds against the queue even when the device is unplugged,
// so without this the job would silently spool and we would report success.
// OpenPrinter succeeds against the queue even when the device is unplugged, so refuse
// on offline or fault flags rather than spool silently and report success.
private static void EnsureReady(IntPtr hPrinter) {
uint needed = 0;
GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out needed);
Expand Down
3 changes: 2 additions & 1 deletion package.json

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions tests/install-manifests.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/** An installed KDS or Server App must open its own page, not the POS dashboard. */
import * as fs from 'fs';
import * as path from 'path';
import { assertEqualOrThrow, assertIncludesOrThrow } from './helpers/test-setup';

const frontend = path.join(__dirname, '../frontend');
const read = (file: string) => fs.readFileSync(path.join(frontend, file), 'utf8');

for (const [page, file] of [
['/kds-standalone', 'kds-manifest.json'],
['/server-standalone', 'server-manifest.json'],
]) {
assertIncludesOrThrow(
read(`src/app${page}/layout.tsx`),
`manifest: '/${file}'`,
`${page} links its own manifest`,
);
const manifest = JSON.parse(read(`public/${file}`));
assertEqualOrThrow(manifest.start_url, page, `the installed app opens ${page}`);
assertEqualOrThrow(manifest.id, page, `${page} installs apart from the POS`);
}

console.log('install manifest tests passed');
process.exit(0);
50 changes: 49 additions & 1 deletion tests/windows-queue-bypass.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
withWindowsQueueBypass,
PRE_SPOOL_REFUSALS,
} from '../main/printers/windows-queue-bypass';
import { printViaNetwork, WINSPOOL_HELPER_SOURCE } from '../main/printers/thermal';
import {
printViaNetwork,
mapWindowsPrinterStatus,
DETECT_WINDOWS_PRINTERS_SCRIPT,
WINSPOOL_HELPER_SOURCE,
} from '../main/printers/thermal';
import { assertEqualOrThrow, assertOrThrow } from './helpers/test-setup';
import { start, type FakeEscposPrinter } from './helpers/fake-escpos-printer';

Expand Down Expand Up @@ -198,6 +203,7 @@ async function main(): Promise<void> {
}

blockingStateOrder();
queueStatusMapping();
console.log('windows queue bypass tests passed');
}

Expand Down Expand Up @@ -230,6 +236,48 @@ function blockingStateOrder(): void {
);
assertOrThrow(!refusable(state(status, attributes)), `status ${status} never uses the bypass`);
}

assertEqualOrThrow(state(0x2), null, 'the generic error flag alone does not block');
for (const [status, attributes, text] of [
[0x12, 0, 'printer is out of paper'],
[0xa, 0, 'printer has a paper jam'],
[0x400002, 0, 'printer cover is open'],
[0x2, 0x400, "printer is set to 'Use Printer Offline' in Windows"],
[0x82, 0, 'printer is offline'],
[0x1002, 0, 'printer is not available'],
[0x100002, 0, 'printer needs attention'],
] as const) {
assertEqualOrThrow(state(status, attributes), text, `status ${status} still blocks`);
}
}

function queueStatusMapping(): void {
for (const [PrinterStatus, expected] of [
[1, 'idle'],
[2, 'idle'],
[3, 'idle'],
[4, 'printing'],
[5, 'idle'],
[6, 'offline'],
[7, 'offline'],
] as const) {
assertEqualOrThrow(
mapWindowsPrinterStatus({ PrinterStatus, WorkOffline: false }),
expected,
`PrinterStatus ${PrinterStatus} maps to ${expected}`,
);
assertEqualOrThrow(
mapWindowsPrinterStatus({ PrinterStatus, WorkOffline: true }),
'offline',
`PrinterStatus ${PrinterStatus} with WorkOffline is offline`,
);
}
assertOrThrow(
/-Property [\w,]*\bWorkOffline\b[\s\S]*Select-Object [\w,]*\bWorkOffline\b/.test(
DETECT_WINDOWS_PRINTERS_SCRIPT,
),
'the detection script queries and returns WorkOffline',
);
}

main().catch((error) => {
Expand Down
Loading