Compare commits

..
4 Commits
Author SHA1 Message Date
Aleksander Grygier 8e23278c7c ui: show only the mention label in generated conversation titles (#33205)
An `@`-mention is sent to the model as a `[name](file:///abs/path)` link, so
a title derived from the first user message inherited the whole link and the
path crowded out the words. Collapse every mention to the text inside its
square brackets when the title comes from the message itself, which covers
both the non-LLM setting and the fallback used when LLM output is unusable.

The LLM prompt still sees the full link, so the model keeps the path.
2026-11-27 20:28:53 +01:00
Aleksander Grygier 6d8a8886fa ui: draw markdown tables with row rules instead of a cell grid (#33195)
A table in a chat column drew a rule around every cell, a band behind the
header and a frame around its scroll wrapper. The lines did the separating
twice over, so the table read heavier than the prose around it.

A hairline under each row carries the structure on its own now: no cell grid,
no header band, no frame, and the outer columns line up with the text above
and below. GFM column alignment arrives as an align attribute, which an
authored text-align beats, so the three values are restated and a
right-aligned column keeps its figures under its header. Numbers take tabular
figures, code in a cell stays one token, and a table of six or more columns
keeps a width a word sits on and scrolls in its wrapper.

The Tables story covers it: alignment, code and links in cells, a list and a
line break in a cell, escaped pipes and an empty cell, and a table wider than
the column.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-27 17:20:19 +01:00
Pedro Cuenca 4c7344447c [Inkling 2] Support nvfp4 pass-through (#33062) 2026-11-27 15:44:37 +01:00
fox5611 3ab385146c CUDA: fix ADD_ID launch for more than 65535 tokens (#33162)
The grid's y dimension came directly from the token count, so ADD_ID
launches with more than 65535 tokens failed with "invalid configuration
argument". NVIDIA and HIP are equally affected, since gridDim.y is
capped at 65535 on both.

Clamp the grid and stride over ne2 in the kernel, matching convert.cu
and pad.cu. Add a test case at 70000 tokens; the existing cases top out
at 129.

Assisted-by: Claude Opus 5
2026-11-27 15:32:42 +01:00
12 changed files with 444 additions and 94 deletions
+67 -11
View File
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
return values
def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
if np.any(scales & 0x80) or np.any(scales == 0x7F):
raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
n_rows = packed.shape[0]
n_blocks = scales.shape[1]
nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
n_super = n_blocks // 4
blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
return blocks.reshape(n_rows, n_super * 36)
def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
if not w13:
return _repack_nvfp4_rows(packed, scales, name, expert)
return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
def _is_inkling2(dir_model: Path) -> bool:
if not (dir_model / "config.json").is_file():
return False
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
class Inkling2Model(TextModel):
model_arch = gguf.MODEL_ARCH.INKLING2
def __init__(self, dir_model: Path, *args, **kwargs):
def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
self._expert_quant: dict[str, dict] = {}
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
quant_path = dir_model / "hf_quant_config.json"
if quant_path.is_file():
with open(quant_path, encoding="utf-8") as f:
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
if name in self._expert_quant:
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
self._expert_quant[name] = group
super().__init__(dir_model, *args, **kwargs)
super().__init__(dir_model, ftype, *args, **kwargs)
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
hp = self.hparams
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
t = gen()
if t.dtype != torch.float32 or tuple(t.shape) != expected:
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
chunks: list[Callable[[], np.ndarray]] = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
if preserve_nvfp4 and cols % 64 != 0:
logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
preserve_nvfp4 = False
chunks: list[Callable[[], np.ndarray]]
if preserve_nvfp4:
assert amax is not None and denominator is not None
a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
if not np.isfinite(a).all() or (a < 0).any():
raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
if not np.isfinite(d).all() or (d <= 0).any():
raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
with np.errstate(over="ignore", invalid="ignore"):
outer_scale = a / d
if not np.isfinite(outer_scale).all():
raise ValueError(f"Inkling2: {name}: non-finite outer scale")
chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
byte_shape = (experts, rows, cols // 64 * 36)
self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
else:
chunks = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
if not nvfp4 and self._fp8_as_q8:
self._fp8_dequantized.add(name)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
for companion in required:
del self.model_tensors[companion]
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
t = gen()
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
self._is_nvfp4 = bool(self._native_experts)
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
@@ -254,6 +300,16 @@ class Inkling2Model(TextModel):
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._native_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
packed, scale = self._native_experts[name]
shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
+14 -12
View File
@@ -2,26 +2,28 @@
static __global__ void add_id_kernel(
const float * src0, const float * src1, const int32_t * src2, float * dst,
int64_t ne0, int64_t ne1,
int64_t ne0, int64_t ne1, int64_t ne2,
size_t nb01, size_t nb02,
size_t nb11,
size_t nb21
) {
const int64_t i1 = blockIdx.x;
const int64_t i2 = blockIdx.y;
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
// gridDim.y is capped at 65535, blocks stride over larger ne2
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
}
}
}
@@ -47,10 +49,10 @@ void ggml_cuda_op_add_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
float * dst_d = (float *)dst->data;
int threads = std::min((int)ne00, 768); // cols
dim3 blocks(ne01, ne02); // n_experts_used, n_tokens
dim3 blocks(ne01, std::min(ne02, (int64_t)65535)); // n_experts_used, n_tokens
add_id_kernel<<<blocks, threads, 0, ctx.stream()>>>(
src0_d, src1_d, src2_d, dst_d,
ne0, ne1,
ne0, ne1, ne2,
nb01, nb02,
nb11,
nb21
+3
View File
@@ -14167,6 +14167,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
// add_id with more than 65535 tokens, exercises the gridDim.y limit
test_cases.emplace_back(new test_add_id(GGML_TYPE_F32, GGML_TYPE_F32, 32, 4, 2, 70000));
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F32}) {
test_cases.emplace_back(new test_sqr (type));
test_cases.emplace_back(new test_sqrt (type));
+92 -9
View File
@@ -648,11 +648,12 @@ class TestInkling2PackedConversion(unittest.TestCase):
decoded = packed.float() * torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
return {"": packed, "_scale": scales}, decoded
def packed_checkpoint(self):
def packed_checkpoint(self, n_ff=None):
"""Layer 0 is NVFP4, layer 1 is MXFP8. Returns the checkpoint tensors, the hf_quant_config groups and the expected GGUF tensors."""
n_ff = self.N_FF if n_ff is None else n_ff
tensors, quant_groups, expected = {}, [], {}
w13_shape = (self.N_EXPERT, 2 * self.N_FF, self.N_EMBD)
w2_shape = (self.N_EXPERT, self.N_EMBD, self.N_FF)
w13_shape = (self.N_EXPERT, 2 * n_ff, self.N_EMBD)
w2_shape = (self.N_EXPERT, self.N_EMBD, n_ff)
for layer, scheme in enumerate(("nvfp4_nearest", "mxfp8_nearest")):
names = []
for projection, shape, target in (("w13", w13_shape, "gate_up"), ("w2", w2_shape, "down")):
@@ -672,13 +673,16 @@ class TestInkling2PackedConversion(unittest.TestCase):
quant_groups.append({"tensors": names, "weight_transform": scheme, "weight_scale_format": "amax_denominator", "weight_block_shape": block_shape})
return tensors, quant_groups, expected
def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False):
def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False, n_ff=None, fp8_as_q8=False, quant_config=None):
"""Writes the checkpoint to path and returns an Inkling2Model on it."""
hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": self.N_FF, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
n_ff = self.N_FF if n_ff is None else n_ff
hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": n_ff, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
if quant_config is not None:
hp["quantization_config"] = quant_config
(path / "config.json").write_text(json.dumps(hp))
(path / "hf_quant_config.json").write_text(json.dumps({"model": {"parameter_groups": quant_groups}}))
save_file(tensors, path / "model.safetensors")
return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager)
return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager, fp8_as_q8=fp8_as_q8)
def test_lookup_semantics(self):
"""The converter decode tables agree with torch.float8_e4m3fn; bytes 127 and 255 are NaN; E2M1 code 8 is -0."""
@@ -688,22 +692,24 @@ class TestInkling2PackedConversion(unittest.TestCase):
self.assertTrue(np.signbit(_E2M1[8]))
def test_mixed_schemes_and_streaming_outtypes(self):
"""Both schemes convert bit-exact to every outtype, lazily, in chunks of at most 128 rows."""
"""Explicit outtypes dequantize both schemes bit-exact, lazily, in chunks of at most 128 rows."""
tensors, quant_groups, expected = self.packed_checkpoint()
outtypes = (
(gguf.LlamaFileType.GUESSED, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.ALL_F32, gguf.GGMLQuantizationType.F32),
(gguf.LlamaFileType.MOSTLY_F16, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.MOSTLY_BF16, gguf.GGMLQuantizationType.BF16),
(gguf.LlamaFileType.MOSTLY_Q8_0, gguf.GGMLQuantizationType.Q8_0),
)
quant_config = {"quant_method": "modelopt", "quant_algo": "NVFP4"}
for eager in (False, True):
for ftype, qtype in outtypes:
with self.subTest(eager=eager, outtype=qtype), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, ftype, eager)
model = self.converter(path, tensors, quant_groups, ftype, eager, quant_config=quant_config)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
model.prepare_tensors()
self.assertTrue(any("[32, 32]" in m and "[1, 32]" in m for m in logs.output))
self.assertFalse(model._is_nvfp4)
infos = model.gguf_writer.tensors[0]
self.assertEqual(infos.keys(), expected.keys())
for name, info in infos.items():
@@ -718,6 +724,83 @@ class TestInkling2PackedConversion(unittest.TestCase):
reference = gguf.quantize(expected[name], qtype)
self.assertEqual(self.written_bytes(info.tensor, path / "tensor.bin"), reference.tobytes(), name)
def test_auto_preserves_nvfp4_and_fp8_as_q8(self):
"""--outtype auto repacks NVFP4 experts lazily with per-expert scales; --fp8-as-q8 stores MXFP8 as Q8_0."""
n_ff = 192
tensors, quant_groups, expected = self.packed_checkpoint(n_ff=n_ff)
for eager in (False, True):
for fp8_as_q8 in (False, True):
with self.subTest(eager=eager, fp8_as_q8=fp8_as_q8), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, eager, n_ff=n_ff, fp8_as_q8=fp8_as_q8)
with self.assertLogs("hf-to-gguf", level="WARNING"):
model.prepare_tensors()
self.assertTrue(model._is_nvfp4)
infos = model.gguf_writer.tensors[0]
expected_keys = set(expected.keys()) | {"blk.0.ffn_gate_up_exps.scale", "blk.0.ffn_down_exps.scale"}
self.assertEqual(infos.keys(), expected_keys)
for target in ("gate_up", "down"):
w_name = f"blk.0.ffn_{target}_exps.weight"
s_name = f"blk.0.ffn_{target}_exps.scale"
w_info, s_info = infos[w_name], infos[s_name]
self.assertEqual(w_info.dtype, gguf.GGMLQuantizationType.NVFP4)
self.assertEqual(tuple(w_info.shape), expected[w_name].shape)
self.assertIsInstance(w_info.tensor, gguf.LazyChunkedTensor)
self.assertEqual(len(w_info.tensor._chunks), self.N_EXPERT)
with self.assertRaises(TypeError):
np.asarray(w_info.tensor)
raw = np.frombuffer(self.written_bytes(w_info.tensor, path / "tensor.bin"), dtype=np.uint8)
byte_shape = (expected[w_name].shape[0], expected[w_name].shape[1], expected[w_name].shape[2] // 64 * 36)
dequant = gguf.dequantize(raw.reshape(byte_shape), gguf.GGMLQuantizationType.NVFP4)
scale = np.asarray(s_info.tensor, dtype=np.float32)
self.assertEqual(s_info.dtype, gguf.GGMLQuantizationType.F32)
self.assertEqual(tuple(s_info.shape), (self.N_EXPERT,))
np.testing.assert_array_equal(dequant * scale[:, None, None], expected[w_name])
mxfp8_name = f"blk.1.ffn_{target}_exps.weight"
mxfp8_info = infos[mxfp8_name]
expected_qtype = gguf.GGMLQuantizationType.Q8_0 if fp8_as_q8 else gguf.GGMLQuantizationType.F16
self.assertEqual(mxfp8_info.dtype, expected_qtype)
reference = gguf.quantize(expected[mxfp8_name], expected_qtype)
self.assertEqual(self.written_bytes(mxfp8_info.tensor, path / "tensor.bin"), reference.tobytes(), mxfp8_name)
def test_auto_falls_back_when_nvfp4_cols_not_multiple_of_64(self):
"""NVFP4 projections whose row width is not a multiple of 64 fall back to dequantization on --outtype auto."""
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=160)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=160)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
model.prepare_tensors()
self.assertTrue(any("not a multiple of 64" in m for m in logs.output))
infos = model.gguf_writer.tensors[0]
self.assertEqual(infos["blk.0.ffn_gate_up_exps.weight"].dtype, gguf.GGMLQuantizationType.NVFP4)
self.assertIn("blk.0.ffn_gate_up_exps.scale", infos)
self.assertEqual(infos["blk.0.ffn_down_exps.weight"].dtype, gguf.GGMLQuantizationType.F16)
self.assertNotIn("blk.0.ffn_down_exps.scale", infos)
def test_auto_nvfp4_rejects_invalid_scales(self):
"""Native NVFP4 preservation rejects negative or NaN block scales and invalid outer scales."""
for bad_byte in (0x80, 0x7F, 0xFF):
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
name = quant_groups[0]["tensors"][0]
tensors[name + "_scale"].view(torch.uint8)[1, 0, 0] = bad_byte
with self.subTest(bad_byte=hex(bad_byte)), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
model.prepare_tensors()
tensor = model.gguf_writer.tensors[0]["blk.0.ffn_gate_up_exps.weight"].tensor
with self.assertRaisesRegex(ValueError, r"w13_weight_scale expert 1"):
self.written_bytes(tensor, path / "tensor.bin")
for suffix, bad_val in (("_amax", -1.0), ("_amax", float("nan")), ("_outer_scale_denominator", 0.0)):
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
name = quant_groups[0]["tensors"][0]
tensors[name + suffix][-1] = bad_val
with self.subTest(suffix=suffix, bad_val=bad_val), tempfile.TemporaryDirectory() as directory:
model = self.converter(Path(directory), tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
with self.assertRaisesRegex(ValueError, "Inkling2:"):
model.prepare_tensors()
def test_projection_and_companions_in_separate_shards(self):
"""A packed weight and its scale, amax and denominator can be in different safetensors shards."""
tensors, quant_groups, expected = self.packed_checkpoint()
@@ -197,39 +197,92 @@
border-radius: 0 0.375rem 0.375rem 0;
}
/* Tables */
/* Tables: one hairline under each row, no cell grid and no outer frame. The
header is set heavier instead of filled, so it reads without a band. */
.markdown-content :global(table) {
/* one line colour for the whole table, so a tinted surface can retint it once */
--table-line: color-mix(in oklch, var(--line-default) 55%, transparent);
width: 100%;
margin: 1.5rem 0;
margin: 1rem 0;
border-collapse: collapse;
border: 1px solid var(--line-default);
border-radius: 0.375rem;
overflow: hidden;
/* a table is reference material, so it sits a step under the prose */
font-size: 0.875rem;
line-height: 1.5;
/* a column of numbers keeps its digits under each other */
font-variant-numeric: tabular-nums;
}
.markdown-content :global(th),
.markdown-content :global(td) {
/* wide gutters carry the column separation that the vertical rules used to */
padding: 0.5rem 1.25rem;
text-align: start;
vertical-align: top;
border-bottom: 1px solid var(--table-line);
}
/* the outer columns line up with the prose above and below the table */
.markdown-content :global(:is(th, td):first-child) {
padding-inline-start: 0;
}
.markdown-content :global(:is(th, td):last-child) {
padding-inline-end: 0;
}
.markdown-content :global(th) {
background: hsl(var(--surface-muted) / 0.3);
border: 1px solid var(--line-default);
padding: 0.5rem 0.75rem;
text-align: left;
/* a header that wraps to two lines keeps its second line on the rule */
padding-block: 0.375rem 0.5rem;
font-weight: 600;
vertical-align: bottom;
}
.markdown-content :global(td) {
border: 1px solid var(--line-default);
padding: 0.5rem 0.75rem;
/* GFM column alignment arrives as an align attribute, which any authored
text-align beats, so the three cases are restated rather than inherited */
.markdown-content :global(:is(th, td)[align='left']) {
text-align: start;
}
.markdown-content :global(tr:nth-child(even)) {
background: hsl(var(--surface-muted) / 0.1);
.markdown-content :global(:is(th, td)[align='center']) {
text-align: center;
}
/* User message markdown should keep table borders visible on light primary backgrounds */
div.markdown-user-content :global(table),
div.markdown-user-content :global(th),
div.markdown-user-content :global(td),
div.markdown-user-content :global(.table-wrapper) {
border-color: currentColor;
.markdown-content :global(:is(th, td)[align='right']) {
text-align: end;
}
/* A table this wide is scrolled either way, so its columns keep a width a word
can sit on instead of crumbling to three lines each */
.markdown-content :global(.table-wrapper table:has(th:nth-child(6)) :is(th, td)) {
min-width: 7rem;
}
/* a flag or a path stays one token in its cell, and the wrapper scrolls */
.markdown-content :global(:is(th, td) code:not(pre code)) {
white-space: nowrap;
}
/* a list restored into a cell keeps the row as tight as its neighbours */
.markdown-content :global(:is(th, td) :is(ul, ol)) {
margin: 0;
padding-inline-start: 1.125rem;
}
.markdown-content :global(:is(th, td) li) {
margin-bottom: 0.125rem;
}
/* A user bubble breaks at anywhere to fit its width, which pulls a table's
columns down to a few letters each; break-word keeps the min-content width */
div.markdown-user-content :global(:is(th, td)) {
overflow-wrap: break-word;
word-break: normal;
}
/* ...and its hairlines stay visible on the tinted bubble background */
div.markdown-user-content :global(table) {
--table-line: color-mix(in oklch, currentColor 25%, transparent);
}
/* Horizontal rules */
@@ -387,21 +440,10 @@ div.markdown-user-content :global(.table-wrapper) {
}
}
/* Advanced table enhancements */
.markdown-content :global(table) {
transition: all 0.2s ease;
}
/* A row lights up under the pointer, to follow a value across a wide table */
@media (hover: hover) and (pointer: fine) {
.markdown-content :global(table:hover) {
box-shadow:
0 4px 6px -1px rgb(0 0 0 / 0.1),
0 2px 4px -2px rgb(0 0 0 / 0.1);
}
.markdown-content :global(th:hover),
.markdown-content :global(td:hover) {
background: var(--surface-muted);
.markdown-content :global(tbody tr:hover td) {
background: color-mix(in oklch, var(--surface-muted) 45%, transparent);
}
}
@@ -411,13 +453,8 @@ div.markdown-user-content :global(.table-wrapper) {
color: inherit;
}
.markdown-user-content :global(table:hover) {
box-shadow: none;
}
.markdown-user-content :global(th:hover),
.markdown-user-content :global(td:hover) {
background: inherit;
.markdown-user-content :global(tbody tr:hover td) {
background: transparent;
}
/* Enhanced blockquotes */
@@ -505,19 +542,18 @@ div.markdown-user-content :global(.table-wrapper) {
border-radius: 50%;
}
/* Scrollable tables */
/* Scrollable tables: the wrapper is only a scroll port. The hairlines belong to
the rows, so a table that fits shows no box around it */
.markdown-content :global(.table-wrapper) {
overflow-x: auto;
margin: 1.5rem 0;
border-radius: 0.5rem;
border: 1px solid var(--line-default);
margin: 1rem 0;
/* a wide table scrolls here, it does not widen the column */
max-width: 100%;
overscroll-behavior-x: contain;
}
.markdown-content :global(.table-wrapper table) {
margin: 0;
border: none;
}
/* Responsive adjustments */
@@ -534,18 +570,10 @@ div.markdown-user-content :global(.table-wrapper) {
font-size: 1.125rem;
}
.markdown-content :global(table) {
font-size: 0.875rem;
}
/* a narrower gutter, and no full-bleed: it hid the outer columns */
.markdown-content :global(th),
.markdown-content :global(td) {
padding: 0.375rem 0.5rem;
}
/* no full-bleed: it hid the outer columns */
.markdown-content :global(.table-wrapper) {
margin: 1rem 0;
padding-inline: 0.875rem;
}
}
@@ -55,6 +55,7 @@ import {
filterByLeafNodeId,
findMessageById,
formatCwdMessage,
generateConversationTitle,
getConversationModel,
isAbortError,
normalizeModelName,
@@ -1484,9 +1485,10 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost {
.trim();
if (!cleanTitle || cleanTitle.length < TITLE_GENERATION.MIN_LENGTH) {
const firstLine = userContent.split('\n').find((l) => l.trim().length > 0);
// the fallback title is the user's own text, so `@`-mentions collapse there too
const firstLine = generateConversationTitle(userContent, true);
cleanTitle = firstLine ? firstLine.trim() : TITLE_GENERATION.FALLBACK;
cleanTitle = firstLine || TITLE_GENERATION.FALLBACK;
}
if (cleanTitle && cleanTitle.length >= TITLE_GENERATION.MIN_LENGTH) {
+1
View File
@@ -295,6 +295,7 @@ export {
getMentionBadgeIconPaths,
getMentionBadgeLabel,
splitMentionSegments,
stripMentionLinks,
buildMentionInsertion
} from './mention-badge';
@@ -85,6 +85,15 @@ export function splitMentionSegments(value: string): MentionTextSegment[] {
return segments;
}
/**
* Collapse every `[name](file://path)` mention to its `name`, dropping the
* path. Used where a mention must read as plain text (a conversation title)
* rather than render as a badge.
*/
export function stripMentionLinks(value: string): string {
return value.replace(fileMentionLinkRe(MENTION_LINK_SCAN_FLAGS), (_match, name: string) => name);
}
export function getMentionBadgeIconPaths(path: string): readonly string[] {
return path.endsWith(DIRECTORY_PATH_SUFFIX)
? MENTION_BADGE_FOLDER_ICON_PATHS
+10 -4
View File
@@ -1,3 +1,4 @@
import { stripMentionLinks } from './mention-badge';
import { NEWLINE } from '#lib/constants/index.ts';
/**
@@ -11,13 +12,18 @@ export function getPreviewText(content: string, max = 150): string {
/**
* Generates a single-line title from a potentially multi-line prompt.
* Uses the first non-empty line if `useFirstLine` is true.
*
* `@`-mentions travel as `[name](file://path)` links, which would otherwise
* dominate a short title, so each one collapses to its `name`.
*/
export function generateConversationTitle(content: string, useFirstLine: boolean = false): string {
if (useFirstLine) {
const firstLine = content.split(NEWLINE).find((line) => line.trim().length > 0);
const stripped = stripMentionLinks(content);
return firstLine ? firstLine.trim() : content.trim();
if (useFirstLine) {
const firstLine = stripped.split(NEWLINE).find((line) => line.trim().length > 0);
return firstLine ? firstLine.trim() : stripped.trim();
}
return content.trim();
return stripped.trim();
}
@@ -1,5 +1,6 @@
<script lang="ts" module>
import { AI_TUTORIAL_MD } from '../fixtures/ai-tutorial.js';
import { MARKDOWN_TABLES_MD } from '../fixtures/markdown-tables.js';
import { MERMAID_DIAGRAMS_MD } from '../fixtures/mermaid-diagrams.js';
import { defineMeta } from '@storybook/addon-svelte-csf';
import { MarkdownContent } from '#lib/components/app/index.ts';
@@ -19,6 +20,48 @@
name="Default"
/>
<Story
args={{ class: 'max-w-[56rem] w-[calc(100vw-2rem)]', content: MARKDOWN_TABLES_MD }}
name="Tables"
play={async ({ canvasElement }) => {
const tables = await waitFor(() => {
const found = [...canvasElement.querySelectorAll('table')];
expect(found).toHaveLength(5);
return found;
});
const numbers = tables[1];
const sizeCell = numbers.querySelectorAll('td')[2];
const sizeHeader = numbers.querySelectorAll('th')[2];
const wrapper = numbers.closest('.table-wrapper') as HTMLElement;
// the lean look: no frame, no filled header, one hairline under each row
await expect(getComputedStyle(wrapper).borderTopWidth).toBe('0px');
await expect(getComputedStyle(sizeHeader).backgroundColor).toBe('rgba(0, 0, 0, 0)');
await expect(getComputedStyle(sizeHeader).borderBottomWidth).toBe('1px');
await expect(getComputedStyle(sizeCell).borderLeftWidth).toBe('0px');
// a right-aligned column stays aligned in the header and in the cells
await expect(getComputedStyle(sizeHeader).textAlign).toBe('end');
await expect(getComputedStyle(sizeCell).textAlign).toBe('end');
// markup models put in cells still renders: a list, and a wrapped line
await expect(canvasElement.querySelector('td ul li')).not.toBeNull();
await expect(canvasElement.querySelector('td br')).not.toBeNull();
// too many columns for the column: the wrapper scrolls, the page does not
const wide = (tables[4] as HTMLElement).closest('.table-wrapper') as HTMLElement;
await expect(wide.scrollWidth).toBeGreaterThan(wide.clientWidth);
await expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(window.innerWidth);
// and it scrolls on a width a model name sits on, rather than crumbling
await expect(wide.querySelector('td')!.getBoundingClientRect().width).toBeGreaterThanOrEqual(
100
);
}}
/>
<Story
args={{ class: 'max-w-[56rem] w-[calc(100vw-2rem)]', content: MERMAID_DIAGRAMS_MD }}
name="Diagrams"
@@ -0,0 +1,48 @@
// Tables the way models write them: mixed column alignment, code and links in
// cells, numbers meant to line up, a cell that wraps, escaped pipes and empty
// cells, and one table too wide for the chat column.
const tick = '`';
export const MARKDOWN_TABLES_MD = `Here are a few tables with different alignments and content:
## Server flags
| Flag | Default | Description |
| :--- | :---: | --- |
| ${tick}--ctx-size${tick} | 4096 | Context size in tokens |
| ${tick}--parallel${tick} | 1 | Slots that serve requests at once |
| ${tick}--jinja${tick} | on | Use the model's own chat template |
## Quantization types
| Type | Bits per weight | Size (7B) | Notes |
| :--- | ---: | ---: | :--- |
| ${tick}Q4_K_M${tick} | 4.85 | 4.07 GB | A good default for most models |
| ${tick}Q5_K_M${tick} | 5.69 | 4.78 GB | A little more quality for a little more memory |
| ${tick}Q8_0${tick} | 8.50 | 7.16 GB | Close to the original weights, see [the docs](https://github.com/ggml-org/llama.cpp) |
| ${tick}F16${tick} | 16.00 | 13.50 GB | **Full** half precision |
## Build status
| Package | Status | Version | Notes |
| :--- | :--- | ---: | :--- |
| ${tick}@ggml-org/llama-ui${tick} | ✅ Passing | 0.4.2 | See [ui/lib/ui](https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/ui) |
| ${tick}llama-storybook${tick} | ⚠️ Flaky | 0.3.0 | **Needs** a rerun on CI |
| ${tick}llama-brand${tick} | ❌ Failing | 0.1.9 | Missing ${tick}BRAND.md${tick} |
## Cells that hold more than a word
| Input | Output | Escaped pipe |
| :--- | :--- | :--- |
| ${tick}a \\| b${tick} | ${tick}a or b${tick} | ✔ |
| | (empty input) | ✘ |
| A list | <ul><li>first</li><li>second</li></ul> | — |
| Two lines | first<br>second | — |
## A wide table
| Model | Family | Parameters | Context | Quantization | Prompt t/s | Generation t/s | Memory | Backend | Notes |
| :--- | :--- | ---: | ---: | :--- | ---: | ---: | ---: | :--- | :--- |
| gpt-oss-20b | GPT-OSS | 20.9B | 131072 | MXFP4 | 1890.4 | 74.2 | 12.1 GB | Metal | Reasoning effort low, medium and high |
| Qwen3-8B | Qwen3 | 8.2B | 40960 | Q4_K_M | 1312.7 | 58.9 | 5.0 GB | Metal | Thinking can be turned off per request |
`;
@@ -0,0 +1,69 @@
import { generateConversationTitle, stripMentionLinks } from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
describe('stripMentionLinks', () => {
it('replaces a mention with its label', () => {
expect(stripMentionLinks('refactor [src/lib](file:///repo/src/lib/) please')).toBe(
'refactor src/lib please'
);
});
it('replaces every mention in the value', () => {
expect(stripMentionLinks('diff [a.m](file:///repo/a.m) with [b.m](file:///repo/b.m)')).toBe(
'diff a.m with b.m'
);
});
it('keeps a directory label and drops its whole path, trailing slash included', () => {
expect(stripMentionLinks('[apps](file:///repo/ui/apps/chat/) has a bug')).toBe(
'apps has a bug'
);
});
it('never leaks a percent-encoded path into the label', () => {
expect(stripMentionLinks('[Shot (1).png](file:///tmp/Shot%20(1).png) is blurry')).toBe(
'Shot (1).png is blurry'
);
});
it('leaves an ordinary markdown link alone', () => {
expect(stripMentionLinks('see [docs](https://example.com/guide)')).toBe(
'see [docs](https://example.com/guide)'
);
});
it('leaves a bare at-sign alone', () => {
expect(stripMentionLinks('mail me at foo@example.com')).toBe('mail me at foo@example.com');
});
});
describe('generateConversationTitle', () => {
it('trims plain content', () => {
expect(generateConversationTitle(' why is my build slow \n')).toBe('why is my build slow');
});
it('drops the file url from a leading mention', () => {
expect(
generateConversationTitle(
'[llama.cpp](file:///Users/me/git/llama.cpp/) how do I build for metal?'
)
).toBe('llama.cpp how do I build for metal?');
});
it('collapses mentions on the picked line when useFirstLine is set', () => {
const content =
'compare [main.c](file:///repo/src/main.c) with [main.cpp](file:///repo/src/main.cpp)\n\nmore detail here';
expect(generateConversationTitle(content, true)).toBe('compare main.c with main.cpp');
});
it('collapses before picking the first line, so a mention-only line still yields text', () => {
expect(generateConversationTitle('\n[notes.md](file:///tmp/notes.md)\nrest', true)).toBe(
'notes.md'
);
});
it('returns an empty title for content that is nothing but whitespace', () => {
expect(generateConversationTitle(' \n\t \n', true)).toBe('');
});
});